- 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
- 41 lines of Python from the credited upstream file 3455.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 shortestMatchingSubstring(self, s: str, p: str) -> int:3 n = len(s)4 a, b, c = p.split('*')5 lpsA = self._getLPS(a + '#' + s)[len(a) + 1:]6 lpsB = self._getLPS(b + '#' + s)[len(b) + 1:]7 lpsC = self._getLPS(c + '#' + s)[len(c) + 1:]8 ans = math.inf9 10 i = 0 11 j = 0 12 k = 0 13 while i + len(b) + len(c) < n:14 while i < n and lpsA[i] != len(a):15 i += 116 while j < n and (j < i + len(b) or lpsB[j] != len(b)):17 j += 118 while k < n and (k < j + len(c) or lpsC[k] != len(c)):19 k += 120 if k == n:21 break22 ans = min(ans, k - i + len(a))23 i += 124 25 return -1 if ans == math.inf else ans26 27 def _getLPS(self, pattern: str) -> list[int]:28 """29 Returns the lps array, where lps[i] is the length of the longest prefix of30 pattern[0..i] which is also a suffix of this substring.31 """32 lps = [0] * len(pattern)33 j = 034 for i in range(1, len(pattern)):35 while j > 0 and pattern[j] != pattern[i]:36 j = lps[j - 1]37 if pattern[i] == pattern[j]:38 lps[i] = j + 139 j += 140 return lps41