- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 79 lines of C++ from the credited upstream file 2851.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 3 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 int numberOfWays(string s, string t, long long k) {22 const int n = s.length();23 const int negOnePowK = (k % 2 == 0 ? 1 : -1); 24 const vector<int> z = zFunction(s + t + t);25 const vector<int> indices = getIndices(z, n);26 vector<int> dp(2); 27 dp[1] = (modPow(n - 1, k) - negOnePowK + kMod) % kMod *28 modPow(n, kMod - 2) % kMod;29 dp[0] = (dp[1] + negOnePowK + kMod) % kMod;30 return accumulate(indices.begin(), indices.end(), 0L,31 [&](long acc, int index) {32 return (acc + dp[index == 0 ? 0 : 1]) % kMod;33 });34 }35 36 private:37 static constexpr int kMod = 1'000'000'007;38 39 long modPow(long x, long n) {40 if (n == 0)41 return 1;42 if (n % 2 == 1)43 return x * modPow(x, n - 1) % kMod;44 return modPow(x * x % kMod, n / 2);45 }46 47 48 49 50 51 vector<int> zFunction(const string& s) {52 const int n = s.length();53 vector<int> z(n);54 int l = 0;55 int r = 0;56 for (int i = 1; i < n; ++i) {57 if (i < r)58 z[i] = min(r - i, z[i - l]);59 while (i + z[i] < n && s[z[i]] == s[i + z[i]])60 ++z[i];61 if (i + z[i] > r) {62 l = i;63 r = i + z[i];64 }65 }66 return z;67 }68 69 70 71 vector<int> getIndices(const vector<int>& z, int n) {72 vector<int> indices;73 for (int i = n; i < n + n; ++i)74 if (z[i] >= n)75 indices.push_back(i - n);76 return indices;77 }78};79