- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 50 lines of Python from the credited upstream file 1923.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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 __init__(self):3 self.BASE = 165_1314 self.HASH = 8_417_508_174_5135 6 def longestCommonSubpath(self, n: int, paths: list[list[int]]) -> int:7 l = 08 r = len(paths[0])9 10 while l < r:11 m = l + (r - l + 1) 212 if self._checkCommonSubpath(paths, m):13 l = m14 else:15 r = m - 116 17 return l18 19 def _checkCommonSubpath(self, paths: list[list[int]], m: int) -> bool:20 """21 Returns True if there's a common subpath of length m for all the paths.22 """23 24 hashSets = [self._rabinKarp(path, m) for path in paths]25 26 27 for subpathHash in hashSets[0]:28 if all(subpathHash in hashSet for hashSet in hashSets):29 return True30 31 return False32 33 def _rabinKarp(self, path: list[int], m: int) -> set[int]:34 """Returns the hash values for subpaths of length m in the path."""35 hashes = set()36 maxPower = 137 hash = 038 39 for i, num in enumerate(path):40 hash = (hash * self.BASE + num) % self.HASH41 if i >= m:42 hash = (hash - path[i - m] * maxPower %43 self.HASH + self.HASH) % self.HASH44 else:45 maxPower = maxPower * self.BASE % self.HASH46 if i >= m - 1:47 hashes.add(hash)48 49 return hashes50