Problem Solving Templates

Copy-paste ready skeletons for each pattern. Fill in the TODO comments with problem-specific logic. These templates represent the cleanest way to implement each pattern — internalize them.

Sliding Window — Variable Size

Expand right freely, shrink left when constraint is violated.

Use when:Longest/shortest subarray with a condition (without repeating, at most K distinct, etc.)
Python template
def sliding_window(nums):
    left = 0
    window_state = {}          # track state inside window
    result = 0

    for right in range(len(nums)):
        # ① EXPAND: add nums[right] to window
        # TODO: update window_state with nums[right]

        # ② SHRINK: while constraint is violated
        while not is_valid(window_state):
            # TODO: remove nums[left] from window_state
            left += 1

        # ③ UPDATE: window [left..right] is valid
        result = max(result, right - left + 1)

    return result
Key insight

Three phases: expand → shrink while invalid → update answer. Each element enters and exits at most once → O(n).

Progress is saved on this device