Sliding Window Pattern: Template + 116 LeetCode Problems

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

  • 12 Easy
  • 74 Medium
  • 30 Hard
  • O(n) time

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.

Sliding Window — Python 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.

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)

#ProblemDifficultyTopics
219Contains Duplicate IIEasyArray, Hash Table, Sliding Window
594Longest Harmonious SubsequenceEasyArray, Hash Table, Counting +2
643Maximum Average Subarray IEasyArray, Sliding Window
1176Diet Plan PerformancePremiumEasyArray, Sliding Window
1652Defuse the BombEasyArray, Sliding Window
1763Longest Nice SubstringEasyBit Manipulation, Hash Table, String +2
1876Substrings of Size Three with Distinct CharactersEasyHash Table, String, Counting +1
1984Minimum Difference Between Highest and Lowest of K ScoresEasyArray, Sorting, Sliding Window
2269Find the K-Beauty of a NumberEasyMath, String, Sliding Window
2379Minimum Recolors to Get K Consecutive Black BlocksEasyString, Sliding Window
2760Longest Even Odd Subarray With ThresholdEasyArray, Sliding Window
2932Maximum Strong Pair XOR IEasyBit Manipulation, Trie, Array +2

Medium (74)

#ProblemDifficultyTopics
3Longest Substring Without Repeating CharactersMediumHash Table, String, Sliding Window
187Repeated DNA SequencesMediumBit Manipulation, Hash Table, String +3
209Minimum Size Subarray SumMediumArray, Binary Search, Prefix Sum +1
395Longest Substring with At Least K Repeating CharactersMediumHash Table, String, Divide and Conquer +1
413Arithmetic SlicesMediumArray, Dynamic Programming, Sliding Window
424Longest Repeating Character ReplacementMediumHash Table, String, Sliding Window
438Find All Anagrams in a StringMediumHash Table, String, Sliding Window
567Permutation in StringMediumHash Table, Two Pointers, String +1
658Find K Closest ElementsMediumArray, Two Pointers, Binary Search +3
713Subarray Product Less Than KMediumArray, Binary Search, Prefix Sum +1
718Maximum Length of Repeated SubarrayMediumArray, Binary Search, Dynamic Programming +3
1004Max Consecutive Ones IIIMediumArray, Binary Search, Prefix Sum +1
1456Maximum Number of Vowels in a Substring of Given LengthMediumString, Sliding Window
1493Longest Subarray of 1's After Deleting One ElementMediumArray, Dynamic Programming, Sliding Window
159Longest Substring with At Most Two Distinct CharactersPremiumMediumHash Table, String, Sliding Window
340Longest Substring with At Most K Distinct CharactersPremiumMediumHash Table, String, Sliding Window
487Max Consecutive Ones IIPremiumMediumArray, Dynamic Programming, Sliding Window
837New 21 GameMediumMath, Dynamic Programming, Sliding Window +1
904Fruit Into BasketsMediumArray, Hash Table, Sliding Window
930Binary Subarrays With SumMediumArray, Hash Table, Prefix Sum +1
978Longest Turbulent SubarrayMediumArray, Dynamic Programming, Sliding Window
1016Binary String With Substrings Representing 1 To NMediumBit Manipulation, Hash Table, String +1
1031Maximum Sum of Two Non-Overlapping SubarraysMediumArray, Dynamic Programming, Sliding Window
1040Moving Stones Until Consecutive IIMediumArray, Math, Sorting +1
1052Grumpy Bookstore OwnerMediumArray, Sliding Window
1100Find K-Length Substrings With No Repeated CharactersPremiumMediumHash Table, String, Sliding Window
1151Minimum Swaps to Group All 1's TogetherPremiumMediumArray, Sliding Window
1156Swap For Longest Repeated Character SubstringMediumHash Table, String, Sliding Window
1208Get Equal Substrings Within BudgetMediumString, Binary Search, Prefix Sum +1
1234Replace the Substring for Balanced StringMediumString, Sliding Window
1248Count Number of Nice SubarraysMediumArray, Hash Table, Math +2
1297Maximum Number of Occurrences of a SubstringMediumHash Table, String, Sliding Window
1343Number of Sub-arrays of Size K and Average Greater than or Equal to ThresholdMediumArray, Sliding Window
1358Number of Substrings Containing All Three CharactersMediumHash Table, String, Sliding Window
1423Maximum Points You Can Obtain from CardsMediumArray, Prefix Sum, Sliding Window
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitMediumQueue, Array, Ordered Set +3
1477Find Two Non-overlapping Sub-arrays Each With Target SumMediumArray, Hash Table, Binary Search +2
1658Minimum Operations to Reduce X to ZeroMediumArray, Hash Table, Binary Search +2
1695Maximum Erasure ValueMediumArray, Hash Table, Sliding Window
1838Frequency of the Most Frequent ElementMediumGreedy, Array, Binary Search +3
1839Longest Substring Of All Vowels in OrderMediumString, Sliding Window
1852Distinct Numbers in Each SubarrayPremiumMediumArray, Hash Table, Sliding Window
1871Jump Game VIIMediumString, Dynamic Programming, Prefix Sum +1
1888Minimum Number of Flips to Make the Binary String AlternatingMediumString, Dynamic Programming, Sliding Window
1918Kth Smallest Subarray SumPremiumMediumArray, Binary Search, Sliding Window
2024Maximize the Confusion of an ExamMediumString, Binary Search, Prefix Sum +1
2067Number of Equal Count SubstringsPremiumMediumHash Table, String, Counting +1
2090K Radius Subarray AveragesMediumArray, Sliding Window
2107Number of Unique Flavors After Sharing K CandiesPremiumMediumArray, Hash Table, Sliding Window
2110Number of Smooth Descent Periods of a StockMediumArray, Math, Two Pointers +2
2134Minimum Swaps to Group All 1's Together IIMediumArray, Sliding Window
2260Minimum Consecutive Cards to Pick UpMediumArray, Hash Table, Sliding Window
2271Maximum White Tiles Covered by a CarpetMediumGreedy, Array, Binary Search +3
2401Longest Nice SubarrayMediumBit Manipulation, Array, Sliding Window
2411Smallest Subarrays With Maximum Bitwise ORMediumBit Manipulation, Array, Binary Search +1
2461Maximum Sum of Distinct Subarrays With Length KMediumArray, Hash Table, Sliding Window
2516Take K of Each Character From Left and RightMediumHash Table, String, Sliding Window
2537Count the Number of Good SubarraysMediumArray, Hash Table, Sliding Window
2555Maximize Win From Two SegmentsMediumArray, Binary Search, Sliding Window
2653Sliding Subarray BeautyMediumArray, Hash Table, Sliding Window
2730Find the Longest Semi-Repetitive SubstringMediumString, Sliding Window
2743Count Substrings Without Repeating CharacterPremiumMediumHash Table, String, Sliding Window
2747Count Zero Request ServersMediumArray, Hash Table, Sorting +1
2762Continuous SubarraysMediumQueue, Array, Ordered Set +3
2779Maximum Beauty of an Array After Applying OperationMediumArray, Binary Search, Sorting +1
2799Count Complete Subarrays in an ArrayMediumArray, Hash Table, Sliding Window
2831Find the Longest Equal SubarrayMediumArray, Hash Table, Binary Search +1
2841Maximum Sum of Almost Unique SubarrayMediumArray, Hash Table, Sliding Window
2875Minimum Size Subarray in Infinite ArrayMediumArray, Hash Table, Prefix Sum +1
2904Shortest and Lexicographically Smallest Beautiful StringMediumString, Sliding Window
2958Length of Longest Subarray With at Most K FrequencyMediumArray, Hash Table, Sliding Window
2962Count Subarrays Where Max Element Appears at Least K TimesMediumArray, Sliding Window
2981Find Longest Special Substring That Occurs Thrice IMediumHash Table, String, Binary Search +2
2982Find Longest Special Substring That Occurs Thrice IIMediumHash Table, String, Binary Search +2

Hard (30)

#ProblemDifficultyTopics
30Substring with Concatenation of All WordsHardHash Table, String, Sliding Window
76Minimum Window SubstringHardHash Table, String, Sliding Window
220Contains Duplicate IIIHardArray, Bucket Sort, Ordered Set +2
239Sliding Window MaximumHardQueue, Array, Sliding Window +2
480Sliding Window MedianHardArray, Hash Table, Sliding Window +1
632Smallest Range Covering Elements from K ListsHardGreedy, Array, Hash Table +3
689Maximum Sum of 3 Non-Overlapping SubarraysHardArray, Dynamic Programming, Prefix Sum +1
683K Empty SlotsPremiumHardBinary Indexed Tree, Segment Tree, Queue +5
727Minimum Window SubsequencePremiumHardString, Dynamic Programming, Sliding Window
862Shortest Subarray with Sum at Least KHardQueue, Array, Binary Search +4
992Subarrays with K Different IntegersHardArray, Hash Table, Counting +1
995Minimum Number of K Consecutive Bit FlipsHardBit Manipulation, Queue, Array +2
1044Longest Duplicate SubstringHardString, Binary Search, Suffix Array +3
1425Constrained Subsequence SumHardQueue, Array, Dynamic Programming +3
1499Max Value of EquationHardQueue, Array, Sliding Window +2
1610Maximum Number of Visible PointsHardGeometry, Array, Math +2
1703Minimum Adjacent Swaps for K Consecutive OnesHardGreedy, Array, Prefix Sum +1
2009Minimum Number of Operations to Make Array ContinuousHardArray, Hash Table, Binary Search +1
2106Maximum Fruits Harvested After at Most K StepsHardArray, Binary Search, Prefix Sum +1
2156Find Substring With Given Hash ValueHardString, Sliding Window, Hash Function +1
2302Count Subarrays With Score Less Than KHardArray, Binary Search, Prefix Sum +1
2398Maximum Number of Robots Within BudgetHardQueue, Array, Binary Search +4
2444Count Subarrays With Fixed BoundsHardQueue, Array, Sliding Window +1
2524Maximum Frequency Score of a SubarrayPremiumHardStack, Array, Hash Table +2
2528Maximize the Minimum Powered CityHardGreedy, Queue, Array +3
2781Length of the Longest Valid SubstringHardArray, Hash Table, String +1
2902Count of Sub-Multisets With Bounded SumHardArray, Hash Table, Dynamic Programming +1
2935Maximum Strong Pair XOR IIHardBit Manipulation, Trie, Array +2
2953Count Complete SubstringsHardHash Table, String, Sliding Window
2968Apply Operations to Maximize Frequency ScoreHardArray, Binary Search, Prefix Sum +2

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the sliding window problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.