Free beta: 60 days of full access, no card needed.84 seats leftSign up free

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy

← Blog
How to prepare

Sliding window algorithm: the template, Python code and how to spot it in a problem

· 2026-10-14 ·

Short answer. The sliding window algorithm keeps two indexes, left and right. Both only move forward. The stretch between them is the window. The right edge grows it. The left edge shrinks it when a condition breaks. Longest or shortest contiguous stretch problems drop from O(n²) to O(n). Below: trigger words, the template, Python code and a traced run.

What is the sliding window algorithm?

A window is a contiguous slice of an array or string. Two indexes define it. Everything between left and right is inside.

A fixed window has a set length and just slides right. A variable window grows and shrinks by a rule. The variable kind shows up more often in interviews.

Both indexes only move right. Each element enters the window once and leaves once. That is why the whole pass costs O(n).

Longest stretch with sum at most 6
longestUnder([2, 1, 5, 1, 1, 2, 1], 6)
2
1
5
1
1
2
1

left
sum = 0limit = 6best = 0

Find the longest stretch whose sum stays at most 6. The window starts empty.

Speed race
Longest run with sum at most 50 in the same 40 positive numbers

Bars: the 40 values. About a quarter of them fit under the limit at once, and the size table keeps that ratio.

One operation is one value read. Every frame, each lane does the same number of operations, so the slow one falls behind.

Every start, then extend O(n²)
0 operations
Growing and shrinking window O(n)
0 operations

 

And with more numbers

Operations for n numbers, and roughly how long they take at 100 million simple operations a second. An estimate from the same count, not a measurement.

n = 1,000
Every start, then extend251K · 2.5 ms
Growing and shrinking window2K · under 1 ms
n = 100,000
Every start, then extend2.5B · 25 s
Growing and shrinking window200K · 2 ms
n = 10,000,000
Every start, then extend25T · 2.9 days
Growing and shrinking window20M · 200 ms

The pattern page: when to use it, and a template in six languages

When does a problem need a sliding window?

  • "Longest substring without repeating characters."
  • "Smallest subarray with sum at least k."
  • "Maximum sum of k consecutive elements."
  • "Does string t contain a permutation of string s."

The shared signal: a contiguous stretch with a cheap property. Moving an edge updates it in O(1). If elements need not be adjacent, a window is the wrong tool.

How does the sliding window template work?

  • Set left = 0. Move right from 0 to n - 1.
  • Add element right to the running state.
  • While the condition is broken, remove element left and move left forward.
  • The window is valid now. Update the answer with its length or content.

The inner while loop does not make it quadratic. Left walks the array once over the whole run.

What does one run look like?

String "abcabcbb", longest substring without repeats. Right reaches a, b, c: window "abc", length 3. Right hits the second a: a repeat. Move left until the first a leaves. Window "bca".

Right hits the second b: left moves past the first b. Window "cab". Right hits the second c: window "abc". Then "cb", then "b". Answer 3.

How do you write a sliding window in Python?

def longest_unique(s):
    seen = set()
    left = best = 0
    for right, ch in enumerate(s):
        while ch in seen:            # condition broken
            seen.remove(s[left])
            left += 1
        seen.add(ch)
        best = max(best, right - left + 1)
    return best

def min_subarray_len(nums, target):
    left = total = 0
    best = float("inf")
    for right, x in enumerate(nums):
        total += x
        while total >= target:      # window valid, try to shrink
            best = min(best, right - left + 1)
            total -= nums[left]
            left += 1
    return 0 if best == float("inf") else best

The second function shrinks while the window is valid. That finds the shortest one. Same skeleton, flipped condition.

How is a sliding window different from two pointers?

TraitSliding windowTwo pointers, opposite ends
DirectionBoth move rightMove towards each other
Looking forA contiguous stretchA pair of elements
Needs sortingNoUsually yes
StateA counter over the windowTwo values
ExampleLongest Substring Without RepeatingTwo Sum II

Three more pairs people confuse, and how to log them, are in two pointers vs sliding window.

How does the sliding window solve Minimum Window Substring?

Given strings s and t. Find the shortest window of s holding every letter of t. Counts included.

Count the letters of t in a dictionary called need. Move right and decrement need for each letter. Keep a counter called missing. When missing hits zero the window is valid. Shrink from the left while it stays valid, and record the best.

Each letter enters and leaves once. Time O(|s| + |t|).

What mistakes break a sliding window?

  • Resetting left to zero on a violation instead of stepping it. That is O(n²).
  • Updating the answer before the window is valid again.
  • Computing the length as right - left instead of right - left + 1.
  • Using a window for a subsequence problem, where elements can be apart.

How do you explain the sliding window in an interview?

Say: the answer is a contiguous stretch. Its property updates in O(1) per edge move. Name the two indexes and the state. Give O(n) and the reason: each index only moves right.

Then show the O(n²) brute force. Say the window removes the recomputation. That is the whole argument.

Drill this pattern on the sliding window page. The fixed-size version lives on the fixed window page.

FAQ

Does a sliding window work with negative numbers?

Not for sum problems. The condition "sum at least k" stops being monotonic. Use prefix sums with a hash map instead.

How do you store the state for strings?

A dictionary from letter to count. Or an array of 26 slots for lowercase letters. The array is faster, the dictionary is more general.

How do you spot a fixed window?

The statement gives a number k and says "consecutive". Then the window is always k long. Left equals right - k + 1.

Free lesson: A window that changes size to fit a rule You write it yourself in the browser, and no account is needed.