Loading section...

At-Most-K: Generalizing Window Constraints

Concepts: pyAtMostK, pyExactlyK, pySubarrayCount

A whole class of sliding window problems uses the phrase 'at most K distinct elements.' Longest substring with at most K distinct characters. Maximum subarray with at most K unique values. Subarrays with at most K odd numbers. The constraint is a ceiling on some property of the window, not an exact value. This is straightforward to implement: maintain a counter, and whenever the number of distinct elements exceeds K, contract left. But there is a deeper trick here that interviewers love to probe: the 'at most K minus at most K-1' identity. Longest Substring with At Most K Distinct Characters The direct implementation: maintain a frequency counter. Contract whenever len(counter) > K (more than K distinct characters in window). Record the window length after each expansion. The at-most-K Ide