Skip to content

Featured article for the topic Sliding window · picked by the needcode team

Sliding window: one pattern, twelve LeetCode problems

Kabir ShahFeatured AuthorPosted · 1 min read

If a problem asks about a contiguous subarray or substring, try a sliding window before anything else.

The template#

def longest_without_repeat(s):
    seen, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        if ch in seen and seen[ch] >= left:
            left = seen[ch] + 1
        seen[ch] = right
        best = max(best, right - left + 1)
    return best

Grow the window with right, shrink it with left until it is valid again, and record the answer. Both pointers only move forward, so it's O(n).

Fixed or variable?#

Window Shrinks when Example
Fixed size k Always, after k Max sum of k elements
Variable The window breaks a rule Longest substring without repeats
Text by Kabir Shah, licensed under CC BY-SA 4.0. You may share and adapt it with credit to the author, under the same licence.

Other approaches to Sliding window

Submit your approach

No other approaches yet. Think you can explain it differently? Write one.

Comments

Loading comments…