Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit — sliding window
Grow right, shrink left the moment the window breaks its invariant. Built for LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.
The window [left, right] is the longest suffix ending at right that still obeys the rule (here: all unique). Last-seen indices tell you exactly how far to jump left.
Algorithm
- Walk
rightacross the string. - If
s[right]was already inside the window, jumpleftpast its last index. - Record the last-seen index and update the best length.
- Time
- O(n)
- Space
- O(σ)
class Solution: def longestContinuousSubarrayWithAbsoluteDiffLessThanOrEqualToLimit(self, s: str) -> int: last: dict[str, int] = {} left = 0 best = 0 for right, ch in enumerate(s): if ch in last and last[ch] >= left: left = last[ch] + 1 last[ch] = right best = max(best, right - left + 1) return best