Sliding Window Subarray Problem
viaLeetCode
Problem Representative sliding-window task: given an array of positive integers and a limit K, find the length of the longest contiguous subarray whose sum is at most K. (The round uses a problem of this shape; master the pattern, not one instance.)
Input / Output
- Input: int array nums, int K.
- Output: the best window length (or the window itself).
Constraints
- n up to 10^5 — O(n) two-pointer expected; O(n^2) enumeration of subarrays fails.
Example
- nums = [3,1,2,1,4], K = 5 → 3 ([1,2,1]).
Expected approach
- Two pointers: extend right, adding to a running sum; while the sum exceeds K, shrink from the left. Track the best window on every valid state. Each pointer moves at most n times → O(n), O(1) space. Know the variants: exact sum with prefix-sum hashmap (handles negatives), at-most-K-distinct with a frequency map, and minimum window meeting a condition (shrink-to-invalid inversion).
asked …