- 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
- 49 lines of Python from the credited upstream file 3036.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 countMatchingSubarrays(self, nums: list[int], pattern: list[int]) -> int:4 def getNum(a: int, b: int) -> int:5 if a < b:6 return 17 if a > b:8 return -19 return 010 11 numsPattern = [getNum(a, b) for a, b in itertools.pairwise(nums)]12 return self._kmp(numsPattern, pattern)13 14 def _kmp(self, nums: list[int], pattern: list[int]) -> int:15 """Returns the number of occurrences of the pattern in `nums`."""16 17 def getLPS(nums: list[int]) -> list[int]:18 """19 Returns the lps array, where lps[i] is the length of the longest prefix of20 nums[0..i] which is also a suffix of this substring.21 """22 lps = [0] * len(nums)23 j = 024 for i in range(1, len(nums)):25 while j > 0 and nums[j] != nums[i]:26 j = lps[j - 1]27 if nums[i] == nums[j]:28 lps[i] = j + 129 j += 130 return lps31 32 lps = getLPS(pattern)33 res = 034 i = 0 35 j = 0 36 while i < len(nums):37 if nums[i] == pattern[j]:38 i += 139 j += 140 if j == len(pattern):41 res += 142 j = lps[j - 1]43 elif j != 0: 44 45 j = lps[j - 1]46 else:47 i += 148 return res49