Pattern 03 of 22

Sliding Window Pattern: Template + 116 LeetCode Problems

Collapse a nested loop over every subarray into a single pass with two indices.

Easy
12
Medium
74
Hard
30
Time
O(n)

What the sliding window pattern is

A sliding window holds one contiguous stretch of the input between two indices, along with a running summary of what is inside it — a sum, a character count, a distinct-element count. Because the summary is updated incrementally as an index moves, advancing the window costs O(1) instead of re-reading it, which is what turns an O(n²) scan of every subarray into one linear pass. The right index always moves forward; the left index moves only while the window violates the constraint, so each element is added once and removed at most once. Two forms cover almost everything: a fixed window slides both ends in lockstep and answers questions about every subarray of length k, while a variable window grows greedily and shrinks from the left until it is legal again, answering questions about the longest or shortest subarray satisfying a condition.

When to use it

  • The answer is a contiguous subarray or substring — not a subsequence, which cannot be described by two indices.
  • You can update the window's summary in O(1) when an element enters or leaves it.
  • The constraint is monotone: if a window is too long or too costly, extending it further cannot fix it.
  • The brute force is two nested loops where the inner one recomputes work the outer one already did.

The sliding window template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 116 problems listed below.

PythonSliding Window template
def longest_valid_window(nums):
    left = 0
    window = 0          # running summary of nums[left : right + 1]
    best = 0

    for right, value in enumerate(nums):
        window += value                 # extend on the right

        while window_is_illegal(window):
            window -= nums[left]        # shrink on the left until legal again
            left += 1

        best = max(best, right - left + 1)

    return best

Complexity characteristics

Time
O(n)
Auxiliary space
O(1) to O(k)

Each index enters the window once and leaves it at most once, so the two pointers together travel at most 2n steps no matter how long any individual window gets — that is what makes a single pass equivalent to the O(n²) scan over every subarray. The space is whatever the running summary costs: O(1) for a sum or a counter, O(k) for a map of the elements currently inside the window, bounded by the alphabet rather than by the input length.

Eyes only

Meet the sliding window problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 116 sliding window LeetCode problems

Every problem in the library the sliding window pattern applies to, grouped by LeetCode's own difficulty rating. 102 of the 116 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (12)

Easy problems
No.Problem
0219Contains Duplicate II
0594Longest Harmonious Subsequence
0643Maximum Average Subarray I
1176Diet Plan PerformancePremium
1652Defuse the Bomb
1763Longest Nice Substring
1876Substrings of Size Three with Distinct Characters
1984Minimum Difference Between Highest and Lowest of K Scores
2269Find the K-Beauty of a Number
2379Minimum Recolors to Get K Consecutive Black Blocks
2760Longest Even Odd Subarray With Threshold
2932Maximum Strong Pair XOR I

Medium (74)

Medium problems
No.Problem
0003Longest Substring Without Repeating Characters
0187Repeated DNA Sequences
0209Minimum Size Subarray Sum
0395Longest Substring with At Least K Repeating Characters
0413Arithmetic Slices
0424Longest Repeating Character Replacement
0438Find All Anagrams in a String
0567Permutation in String
0658Find K Closest Elements
0713Subarray Product Less Than K
0718Maximum Length of Repeated Subarray
1004Max Consecutive Ones III
1456Maximum Number of Vowels in a Substring of Given Length
1493Longest Subarray of 1's After Deleting One Element
0159Longest Substring with At Most Two Distinct CharactersPremium
0340Longest Substring with At Most K Distinct CharactersPremium
0487Max Consecutive Ones IIPremium
0837New 21 Game
0904Fruit Into Baskets
0930Binary Subarrays With Sum
0978Longest Turbulent Subarray
1016Binary String With Substrings Representing 1 To N
1031Maximum Sum of Two Non-Overlapping Subarrays
1040Moving Stones Until Consecutive II
1052Grumpy Bookstore Owner
1100Find K-Length Substrings With No Repeated CharactersPremium
1151Minimum Swaps to Group All 1's TogetherPremium
1156Swap For Longest Repeated Character Substring
1208Get Equal Substrings Within Budget
1234Replace the Substring for Balanced String
1248Count Number of Nice Subarrays
1297Maximum Number of Occurrences of a Substring
1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
1358Number of Substrings Containing All Three Characters
1423Maximum Points You Can Obtain from Cards
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
1477Find Two Non-overlapping Sub-arrays Each With Target Sum
1658Minimum Operations to Reduce X to Zero
1695Maximum Erasure Value
1838Frequency of the Most Frequent Element
1839Longest Substring Of All Vowels in Order
1852Distinct Numbers in Each SubarrayPremium
1871Jump Game VII
1888Minimum Number of Flips to Make the Binary String Alternating
1918Kth Smallest Subarray SumPremium
2024Maximize the Confusion of an Exam
2067Number of Equal Count SubstringsPremium
2090K Radius Subarray Averages
2107Number of Unique Flavors After Sharing K CandiesPremium
2110Number of Smooth Descent Periods of a Stock
2134Minimum Swaps to Group All 1's Together II
2260Minimum Consecutive Cards to Pick Up
2271Maximum White Tiles Covered by a Carpet
2401Longest Nice Subarray
2411Smallest Subarrays With Maximum Bitwise OR
2461Maximum Sum of Distinct Subarrays With Length K
2516Take K of Each Character From Left and Right
2537Count the Number of Good Subarrays
2555Maximize Win From Two Segments
2653Sliding Subarray Beauty
2730Find the Longest Semi-Repetitive Substring
2743Count Substrings Without Repeating CharacterPremium
2747Count Zero Request Servers
2762Continuous Subarrays
2779Maximum Beauty of an Array After Applying Operation
2799Count Complete Subarrays in an Array
2831Find the Longest Equal Subarray
2841Maximum Sum of Almost Unique Subarray
2875Minimum Size Subarray in Infinite Array
2904Shortest and Lexicographically Smallest Beautiful String
2958Length of Longest Subarray With at Most K Frequency
2962Count Subarrays Where Max Element Appears at Least K Times
2981Find Longest Special Substring That Occurs Thrice I
2982Find Longest Special Substring That Occurs Thrice II

Hard (30)

Hard problems
No.Problem
0030Substring with Concatenation of All Words
0076Minimum Window Substring
0220Contains Duplicate III
0239Sliding Window Maximum
0480Sliding Window Median
0632Smallest Range Covering Elements from K Lists
0689Maximum Sum of 3 Non-Overlapping Subarrays
0683K Empty SlotsPremium
0727Minimum Window SubsequencePremium
0862Shortest Subarray with Sum at Least K
0992Subarrays with K Different Integers
0995Minimum Number of K Consecutive Bit Flips
1044Longest Duplicate Substring
1425Constrained Subsequence Sum
1499Max Value of Equation
1610Maximum Number of Visible Points
1703Minimum Adjacent Swaps for K Consecutive Ones
2009Minimum Number of Operations to Make Array Continuous
2106Maximum Fruits Harvested After at Most K Steps
2156Find Substring With Given Hash Value
2302Count Subarrays With Score Less Than K
2398Maximum Number of Robots Within Budget
2444Count Subarrays With Fixed Bounds
2524Maximum Frequency Score of a SubarrayPremium
2528Maximize the Minimum Powered City
2781Length of the Longest Valid Substring
2902Count of Sub-Multisets With Bounded Sum
2935Maximum Strong Pair XOR II
2953Count Complete Substrings
2968Apply Operations to Maximize Frequency Score

Sliding Window pattern FAQ

What is the sliding window pattern?

A sliding window holds one contiguous stretch of the input between two indices, along with a running summary of what is inside it — a sum, a character count, a distinct-element count.

How many LeetCode problems use the sliding window pattern?

This page lists 116 LeetCode problems that the sliding window pattern applies to: 12 Easy, 74 Medium and 30 Hard. 102 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the sliding window pattern?

O(n) time and O(1) to O(k) space. Each index enters the window once and leaves it at most once, so the two pointers together travel at most 2n steps no matter how long any individual window gets — that is what makes a single pass equivalent to the O(n²) scan over every subarray. The space is whatever the running summary costs: O(1) for a sum or a counter, O(k) for a map of the elements currently inside the window, bounded by the alphabet rather than by the input length.

When should I use the sliding window pattern in an interview?

The answer is a contiguous subarray or substring — not a subsequence, which cannot be described by two indices. You can update the window's summary in O(1) when an element enters or leaves it.

Which sliding window problem should I start with?

LeetCode 219. Contains Duplicate II is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to sliding window?

Two Pointers, Prefix Sum, Hash Map, Monotonic Stack. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.