Perform an operation on a specific window size of a given data structure.
When to use
- Input is an array, string, or lined list
- Find the substring, subarray, or value to satisfy a condition
- Longest subarray containing all 1s.
- Max sum
- Exactly k distinct
- Longest without repeating
- Minimum size subarray ≥ S.
Methodology
- Start from the 1st element
- Keep shifting right by one element
- Adjust the length of the window according to the problem
- In some cases, the window size remains constant
- In other cases the sizes grows or shrinks.
Idea
- Maintain a window
[i..j]
that satisfies (or almost satisfies) your condition. - Expand
j
until the condition is violated or met - Then contract
i
as far as possible while still (barely) satisfying the condition.
Sketch
- Initialize
i = 0, currentSum = 0
. - For
j
in0..n–1
:- Add
arr[j]
tocurrentSum
. - While
currentSum ≥ S
:- Update
minLength = min(minLength, j – i + 1)
. - Subtract
arr[i++]
fromcurrentSum
.
- Update
- Add
- If
minLength
was never updated, no solution; else returnminLength
.
Time: O(n), since each element enters/exits window at most once. Space: O(1), or O(k) if you track counts of distinct elements via a hash.