- 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
- 53 lines of Python from the credited upstream file 2851.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit 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 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def numberOfWays(self, s: str, t: str, k: int) -> int:21 MOD = 1_000_000_00722 n = len(s)23 negOnePowK = 1 if k % 2 == 0 else -1 24 z = self._zFunction(s + t + t)25 26 27 indices = [i - n for i in range(n, n + n) if z[i] >= n]28 dp = [0] * 2 29 dp[1] = (pow(n - 1, k, MOD) - negOnePowK) * pow(n, MOD - 2, MOD)30 dp[0] = dp[1] + negOnePowK31 return sum(dp[0] if index == 0 else dp[1] for index in indices) % MOD32 33 def _zFunction(self, s: str) -> list[int]:34 """35 Returns the z array, where z[i] is the length of the longest prefix of36 s[i..n) which is also a prefix of s.37 38 https:cp-algorithms.com/string/z-function.html39 """40 n = len(s)41 z = [0] * n42 l = 043 r = 044 for i in range(1, n):45 if i < r:46 z[i] = min(r - i, z[i - l])47 while i + z[i] < n and s[z[i]] == s[i + z[i]]:48 z[i] += 149 if i + z[i] > r:50 l = i51 r = i + z[i]52 return z53