Count Subarrays With Fixed Bounds — sliding window
Grow right, shrink left the moment the window breaks its invariant. Built for LeetCode 2444. Count Subarrays With Fixed Bounds.
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 countSubarraysWithFixedBounds(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