The sliding window pattern

Master the sliding window pattern to optimize array and string problems from O(N²) to O(N). Learn fixed and dynamic window templates, common pitfalls, and real interview examples.

intermediate11 min readBy CureBugs EditorialUpdated 5 Nov 2026

If you have ever written nested loops to check every possible subarray and watched your code time out during an online assessment, you need the sliding window pattern. At its core, sliding window is an optimization technique that transforms $O(N^2)$ or $O(N^3)$ brute-force solutions into elegant $O(N)$ algorithms. It achieves this by reusing the work done in previous steps rather than recalculating overlapping data from scratch. In Indian tech interviews, from service companies' coding rounds to Amazon and Flipkart, this pattern is a staple for string and array manipulation rounds.

When to use this pattern

Recognizing when to apply the sliding window pattern is half the battle. Interviewers rarely tell you to use it directly. Instead, look for these strong signals in the problem statement:

  1. The "Contiguous" Keyword: The problem asks you to find a "subarray" or "substring". Unlike subsequences (which can skip elements), subarrays and substrings must be strictly contiguous. Sliding window is purpose-built for contiguous elements.
  2. Min/Max/Longest/Shortest: You are asked to optimize a metric, such as finding the longest substring with a certain property, or the minimum length subarray that sums to a target.
  3. Linear Data Structures: The input is an array, string, or occasionally a linked list.
  4. Monotonicity (Crucial for dynamic windows): Adding an element to the window should predictably change the state (e.g., adding positive numbers always increases the sum). If adding an element can either help or hurt unpredictably (like adding negative numbers to a sum), sliding window might fail.

The core idea

Imagine a physical window frame sliding over a sequence of numbers. You can only see the numbers inside the frame.

Instead of picking up the frame and placing it down on every possible starting position (which is what a nested loop does), you slide the right edge of the frame to include a new element, and slide the left edge to remove an old element.

There are two main types of sliding windows:

Window TypeCharacteristicExample Problem
Fixed-sizeThe window size k remains strictly constant. You add one element on the right and remove exactly one on the left.Maximum sum of a contiguous subarray of size k.
Dynamic-sizeThe window expands on the right until a condition is met (or violated), then shrinks from the left to restore the condition.Longest substring without repeating characters.

Here is a visual representation of a dynamic window expanding and shrinking:

Template

Memorizing a robust template prevents off-by-one errors during high-pressure interviews. Here is the standard template for a dynamic sliding window.

def sliding_window_template(arr):
    left = 0
    best_ans = 0 # or float('inf') for minimums
    
    for right in range(len(arr)):
        # 1. Add the current element arr[right] to the window state
        
        # 2. While the window violates the problem's condition, shrink it
        while invalid_condition():
            # Remove arr[left] from the window state
            left += 1
            
        # 3. Update the best answer (can also happen inside the while loop for some problems)
        best_ans = max(best_ans, right - left + 1)
        
    return best_ans

Worked examples

Let's apply this template to three classic interview problems.

1. Longest Substring Without Repeating Characters

Problem: Given a string s, find the length of the longest substring without repeating characters.

Approach: We use a dynamic sliding window. We maintain a set (or a boolean array/hash map) to keep track of the characters currently in our window.

  1. We expand the window by moving right and adding s[right] to our set.
  2. If s[right] is already in the set, our window is invalid. We must shrink the window from the left until the duplicate character is removed.
  3. At the end of each valid step, we update our maximum length.
def lengthOfLongestSubstring(s: str) -> int:
    char_set = set()
    left = 0
    max_len = 0
    
    for right in range(len(s)):
        # While the character is already in the window, shrink from left
        while s[right] in char_set:
            char_set.remove(s[left])
            left += 1
            
        # Add the current character and update max_len
        char_set.add(s[right])
        max_len = max(max_len, right - left + 1)
        
    return max_len

Complexity:

  • Time: $O(N)$ where $N$ is the length of the string. Each character is processed at most twice (once added, once removed).
  • Space: $O(min(N, M))$ where $M$ is the size of the character set (e.g., 26 for lowercase English letters, 128 for ASCII).

2. Minimum Size Subarray Sum

Problem: Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there is no such subarray, return 0.

Approach: This problem asks for a minimum length, which slightly changes where we update our answer.

  1. Expand the window by adding nums[right] to a running window_sum.
  2. When window_sum >= target, our condition is met! Since we want the minimum length, we record the current window length, and then try to shrink the window from the left to see if we can find an even smaller valid window.
def minSubArrayLen(target: int, nums: list[int]) -> int:
    left = 0
    window_sum = 0
    min_len = float('inf')
    
    for right in range(len(nums)):
        window_sum += nums[right]
        
        # While the window is valid, record the answer and try to shrink it
        while window_sum >= target:
            min_len = min(min_len, right - left + 1)
            window_sum -= nums[left]
            left += 1
            
    return min_len if min_len != float('inf') else 0

Complexity:

  • Time: $O(N)$ because the left and right pointers only move forward.
  • Space: $O(1)$ as we only use a few integer variables.

3. Max Consecutive Ones III

Problem: Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array if you can flip at most k 0s.

Approach: Instead of thinking about "flipping" zeroes, reframe the problem: Find the longest contiguous subarray that contains at most k zeroes.

  1. Expand the window to the right. If we encounter a 0, increment our zero_count.
  2. If zero_count > k, our window is invalid. We must shrink from the left until we remove a 0 from the window.
  3. Update the maximum length.
def longestOnes(nums: list[int], k: int) -> int:
    left = 0
    zero_count = 0
    max_len = 0
    
    for right in range(len(nums)):
        if nums[right] == 0:
            zero_count += 1
            
        while zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
            
        max_len = max(max_len, right - left + 1)
        
    return max_len

Variations and pitfalls

The Negative Number Trap

In the Minimum Size Subarray Sum problem above, we explicitly stated the array contained positive integers. Why? Because with positive integers, expanding the window guarantees the sum increases, and shrinking it guarantees the sum decreases. This monotonicity is what allows us to safely move the left pointer.

If the array contains negative numbers (e.g., [3, -1, 4, -2, 5]), adding an element might decrease the sum. You can no longer guarantee that shrinking the window is the right move when the sum exceeds the target. If you see negative numbers in a subarray sum problem, immediately abandon the sliding window and switch to Prefix Sums and Hashing.

Where to update the answer

Notice the difference between Example 1 (Longest Substring) and Example 2 (Minimum Subarray Sum):

  • When finding a maximum, we update the answer outside the while loop, after the window has been made valid.
  • When finding a minimum, we update the answer inside the while loop, because the while loop condition itself represents a valid state that we are trying to minimize.

Fixed-size windows

Sometimes the problem dictates a fixed window size k. In these cases, you don't need a while loop to shrink the window. Instead, you check if right - left + 1 == k. If it is, you record the answer, remove the left element, and increment left by 1.

Practice checklist

To truly master this pattern, try solving these variations on your own:

  1. Fixed Window: Find the maximum average subarray of size k.
  2. String Anagrams: Find all starting indices of anagrams of string p in string s (requires a frequency map as the window state).
  3. Multiple Conditions: Longest substring with at most k distinct characters.

Once you internalize the template and understand the negative number pitfall, sliding window problems will become some of the easiest and most predictable questions you can encounter in an interview.

Mock interview

Solve one like this with an interviewer watching

Getting the answer alone is half the round. The other half is clarifying the problem, explaining your approach, coding while you talk and handling the follow-up. Try it on a problem you haven't seen.

  • A timed problem in a real editor, judged on hidden tests
  • Hints if you ask, and they count against you like they would in the room
  • A scored report that quotes your answers and says what to fix
Start a mock coding round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
DSA patterns•intermediate

The two pointers pattern

15 min read
DSA patterns•intermediate

Dynamic programming on subsequences

12 min read
DSA patterns•intermediate

Prefix sums and hashing

11 min read
DSA patterns•intermediate

The monotonic stack pattern

12 min read
The sliding window pattern · CureBugs