Description

Sliding window is when you want to find the max/min consecutive length of an array, with some validation rule.

Runtime

best case O(n)
worst case O(2n)

Visualization

Sliding Window-1783444297789.webp|673

Pseudocode

l is 0
r is 0
state is 0

for every item r in nums:
	add the value of r to the state
	while state is not valid:
		save value for min
		subtract the value of l from the state
		increase l
	save value for max
	increase r 

Code

def sliding_window(nums, k):
    left = 0
    state = 0        # track window property (count, sum, etc.)
    res = 0
    for right in range(len(nums)):
        # 1. Expand: add nums[right] to window
        state += ...

        # 2. Shrink: while window is invalid
        while window_is_invalid(state, k):
            state -= ...   # remove nums[left]
            left += 1

        # 3. Update answer (window is valid here)
        res = max(res, right - left + 1)
    return res
# if you want to check smallest
while window_is_valid(state):
    res = min(res, right - left + 1)
    state -= ...  # remove nums[left]
    left += 1