- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 53 lines of Python from the credited upstream file 3006.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 def beautifulIndices(self, s: str, a: str, b: str, k: int) -> list[int]:3 ans = []4 indicesA = self._kmp(s, a)5 indicesB = self._kmp(s, b)6 indicesBIndex = 0 7 8 for i in indicesA:9 10 11 while indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i < -k:12 indicesBIndex += 113 if indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i <= k:14 ans.append(i)15 16 return ans17 18 def _kmp(self, s: str, pattern: str) -> list[int]:19 """Returns the starting indices of all occurrences of the pattern in `s`."""20 21 def getLPS(pattern: str) -> list[int]:22 """23 Returns the lps array, where lps[i] is the length of the longest prefix of24 pattern[0..i] which is also a suffix of this substring.25 """26 lps = [0] * len(pattern)27 j = 028 for i in range(1, len(pattern)):29 while j > 0 and pattern[j] != pattern[i]:30 j = lps[j - 1]31 if pattern[i] == pattern[j]:32 lps[i] = j + 133 j += 134 return lps35 36 res = []37 lps = getLPS(pattern)38 i = 0 39 j = 0 40 while i < len(s):41 if s[i] == pattern[j]:42 i += 143 j += 144 if j == len(pattern):45 res.append(i - j)46 j = lps[j - 1]47 elif j != 0: 48 49 j = lps[j - 1]50 else:51 i += 152 return res53