← All topics

Sliding Window

A specialization of two pointers for 'best contiguous subarray/substring' problems. Grow a window from the right, shrink it from the left when it breaks some constraint, and track the best window seen -- all in one pass instead of re-scanning every subarray.

121. Best Time to Buy and Sell Stock

Given an array of daily prices, find the maximum profit from buying on one day and selling on a later day (or 0 if no profit is possible).

def max_profit(prices):
    min_price = prices[0]
    best = 0
    for p in prices[1:]:
        best = max(best, p - min_price)
        min_price = min(min_price, p)
    return best

The 'window' here is implicit: the left edge is the cheapest price seen so far, the right edge is today. One pass keeps both the running minimum and the best profit against it updated together.

219. Contains Duplicate II

Given an array nums and an integer k, return true if there are two distinct indices i and j such that nums[i] == nums[j] and abs(i - j) <= k.

def contains_nearby_duplicate(nums, k):
    window = set()
    for i, n in enumerate(nums):
        if n in window:
            return True
        window.add(n)
        if len(window) > k:
            window.remove(nums[i - k])
    return False

A set holds exactly the last k elements -- the sliding window. Each step checks membership before inserting, then evicts the element that just fell outside the window on the left.

Same topic, no training wheels. Solve these on your own before you check the editorial.