- 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
- 54 lines of Python from the credited upstream file 3008.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 3 def beautifulIndices(self, s: str, a: str, b: str, k: int) -> list[int]:4 ans = []5 indicesA = self._kmp(s, a)6 indicesB = self._kmp(s, b)7 indicesBIndex = 0 8 9 for i in indicesA:10 11 12 while indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i < -k:13 indicesBIndex += 114 if indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i <= k:15 ans.append(i)16 17 return ans18 19 def _kmp(self, s: str, pattern: str) -> list[int]:20 """Returns the starting indices of all occurrences of the pattern in `s`."""21 22 def getLPS(pattern: str) -> list[int]:23 """24 Returns the lps array, where lps[i] is the length of the longest prefix of25 pattern[0..i] which is also a suffix of this substring.26 """27 lps = [0] * len(pattern)28 j = 029 for i in range(1, len(pattern)):30 while j > 0 and pattern[j] != pattern[i]:31 j = lps[j - 1]32 if pattern[i] == pattern[j]:33 lps[i] = j + 134 j += 135 return lps36 37 lps = getLPS(pattern)38 res = []39 i = 0 40 j = 0 41 while i < len(s):42 if s[i] == pattern[j]:43 i += 144 j += 145 if j == len(pattern):46 res.append(i - j)47 j = lps[j - 1]48 elif j != 0: 49 50 j = lps[j - 1]51 else:52 i += 153 return res54