Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold — sliding window
Grow right, shrink left the moment the window breaks its invariant. Built for LeetCode 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold.
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 numberOfSubArraysOfSizeKAndAverageGreaterThanOrEqualToThreshold(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