Quick Answer

Apply sliding window technique to items in a row in 2 ways. Choose a fixed window or a variable window. Fixed window uses one size and slides along the list. Variable window grows and shrinks by a rule. Both reuse work and take O(n) time. Brute force repeats work and takes O(n times k) time. Test your code on a list shorter than the window.

Sliding window technique speeds up problems about a stretch of items in a row. Instead of adding every group from scratch you slide a window across the list. You drop the item that exits and add the item that enters.

Most slow answers repeat the same additions again and again. Sliding window technique reuses them. Waste comes first below and the fix follows.

What Is the Sliding Window Technique?

Sliding window technique is a method that moves a fixed or flexible range across a list and updates the answer from the item that exits and the item that enters. It cuts repeated work so many problems drop from O(n times k) to O(n) time.

Problems it solves are about items that sit side by side in a list. Examples are the biggest total of any 5 neighbouring numbers and the longest stretch with no repeated letter. Many tutorials call the same idea the sliding window algorithm and both names mean one method.

Picture a window that shows a few items at once. Slide the window along the list one step at a time. One item exits at the back and one item joins at the front.

You update only that small difference and not the entire window. Reuse is the main idea. Sliding window works on arrays in data structure or any list with a clear order.

Why Does Brute Force Waste Work Without Sliding Window?

Take the list [2, 1, 5, 1, 3, 2] and ask for the maximum sum over any 3 numbers in a row. Brute force adds every group of 3 from scratch. Positions 1 to 3 come first and positions 2 to 4 come next.

Two groups in a row share all but one number. Brute force adds the shared numbers again anyway. For a window of size k over n items that costs about n times k additions.

Sliding window technique sees the overlap and adds only the new number. Why count shared numbers twice?

How Does Sliding Window Work Step by Step?

Find the largest sum of 3 numbers in a row in [2, 1, 5, 1, 3, 2]. Watch how the window reuses the last sum.

  1. Add the first 3 numbers. 2 plus 1 plus 5 gives 8.
  2. Slide one step right. Remove 2 and add 1. New sum is 8 minus 2 plus 1, which equals 7.
  3. Slide again. Remove 1 and add 3. New sum is 7 minus 1 plus 3, which equals 9.
  4. Slide once more. Remove 5 and add 2. New sum is 9 minus 5 plus 2, which equals 6.

Window sums are 8, 7, 9 and 6. Biggest sum is 9. Every slide took one subtraction and one addition and not a fresh count of 3.

How Do You Code the Sliding Window in Python and C++?

Code for the sliding window algorithm adds the first window and then slides by subtracting the exiting item and adding the entering item. Python version comes first.

def max_sum(arr, k):
    if k > len(arr):
        return None                    # window is larger than the list
    window = sum(arr[:k])              # sum of the first window
    best = window
    for i in range(k, len(arr)):
        window += arr[i] - arr[i - k]  # add new, drop old
        best = max(best, window)
    return best

print(max_sum([2, 1, 5, 1, 3, 2], 3))   # prints 9

Loop line does all the work. Loop line adds the entering item and subtracts the exiting item in one step. C++ version below uses the same idea.

#include <climits>

int maxSum(int arr[], int n, int k) {
    if (k > n) return INT_MIN;         // window is larger than the list
    int window = 0;
    for (int i = 0; i < k; i++) window += arr[i];
    int best = window;
    for (int i = k; i < n; i++) {
        window += arr[i] - arr[i - k]; // add new, drop old
        if (window > best) best = window;
    }
    return best;
}

Both versions build the first window once and then update it with one add and one subtract per step. One add and one subtract per slide make the scan O(n). Go to the post on time complexity and Big O for the reason.

Tested. Python 3.13 and g++ 13.3 executed both versions. Both printed 9 for the sample list. Python version also matched brute force on 2,000 random lists.

Table below compares the cost of every sliding window algorithm style with brute force. Variable window with a dictionary needs extra space for the letters it stores.

WayTimeExtra space
Brute forceO(n times k)O(1)
Fixed windowO(n)O(1)
Variable window with a dictionaryO(n)O(m) for m different letters

Do You Know? Brute force needs about n times k additions. On a list of 100,000 items with a window of 1,000 items that means 100 million additions. Sliding window needs about 100,000 additions, which is 1,000 times fewer.

How Do You Spot a Sliding Window Problem?

Look for the words in the problem statement. Three clues together point to sliding window technique.

  • Items in a row. Words like subarray, substring or consecutive appear.
  • One answer about a range. Problem asks for a sum, a count or a length of that range.
  • Size or rule. Words like size k, at most or without repeating set the window.

Items spread across the list break the first clue. Use another method for those problems.

What Are the Two Types of Sliding Window?

Choose the type first and the code follows. Fixed window and variable window are two forms of sliding window technique.

DetailFixed windowVariable window
Window sizeSame from start to endGrows and shrinks
What sets the sizeA number k in the problemA rule like no repeated letter
Typical answerLargest sum or averageLongest or shortest range
TimeO(n)O(n)

Method #1: Fixed Window (Set Size, Sum Problems)

Who it suits. Beginners who solve sums of a set number of items. Extra application. None, because Python or a C++ compiler is enough.

Fixed window uses the same size from start to end, like the sum of 3 numbers above. Slide the window across the list and update the sum at every step.

Open the Max Sum Window visualiser to watch a fixed window move.

Method #2: Variable Window (Grows and Shrinks by a Rule)

Who it suits. Learners who are ready for string and range rules. Extra application. None, because the Python console is enough.

Variable window adjusts its size by a rule, like the longest stretch with no repeated letter. Window grows while the rule applies and shrinks when the rule breaks.

Take the text abcbdea and move the right edge letter by letter. At the second b (index 3) the earlier b sits at index 1. Left edge jumps to index 2 and the window becomes cb.

Letters d, e and a join next. First a sits at index 0, which is outside the window. Window grows to cbdea with length 5.

def longest_unique(text):
    seen = {}
    left = 0
    best_len, best_start = 0, 0
    for right, letter in enumerate(text):
        if letter in seen and seen[letter] >= left:
            left = seen[letter] + 1
        seen[letter] = right
        if right - left + 1 > best_len:
            best_len = right - left + 1
            best_start = left
    return text[best_start:best_start + best_len]

print(longest_unique("abcbdea"))   # prints cbdea

Left edge and right edge are two pointers. Open the two pointers lesson for the wider idea and the Longest Unique Substring visualiser to watch this example.

Which Mistakes Break Sliding Window Code?

Two mistakes cause most wrong answers. Both appear in the code above and both are easy to test.

  • Window bigger than the list. Python code adds the entire list when k is too large. Guard code returns None before that happens.
  • Left edge that moves backward. Variable window must move the left edge only forward. Dropping the check seen[letter] >= left breaks that rule.

Results from executing the longest unique letters code with and without that check follow.

TextCorrect answerAnswer without the check
abbaabbba
tmmzuxtmzuxtmmzuxt

Answers in the last column repeat a letter so they are wrong. Always test variable window code on texts with a repeated letter far apart.

Which Problems Practice Sliding Window Technique?

Solve these LeetCode problems in order. Every problem uses one type from this post.

  1. Maximum Average Subarray I uses a fixed window.
  2. Longest Substring Without Repeating Characters uses a variable window and matches the example above.
  3. Minimum Size Subarray Sum uses a variable window that shrinks once the sum is large enough.

Frequently Asked Questions

Is Sliding Window Algorithm Faster Than Brute Force?

Yes. Sliding window technique takes O(n) time because every item enters and exits the window once. Brute force takes O(n times k) time because it adds every window from scratch.

Is Sliding Window Limited to Arrays?

No. Sliding window works on any ordered sequence, like an array or a string. Items need a fixed order so the window can slide across them.

Is a Variable Window the Same as Two Pointers?

Yes, almost. Variable window means two pointers that mark the left and right edges. Two pointers is the wider idea and sliding window is one common use of it.

Should You Use Sliding Window When Items Do Not Sit Side by Side?

No. Items side by side are the clue for sliding window technique. Items spread across a list need a different method.

Does Sliding Window Give the Same Answer as Brute Force?

Yes. Both return the same answer and sliding window needs fewer steps. Check the claim on [2, 1, 5, 1, 3, 2] with k equal to 3, where both return 9.

Can Sliding Window Return the Items and Not the Sum Alone?

Yes. Store the left edge whenever the best result grows. Variable window code above does this and returns the text cbdea for abcbdea.

Can You Test Sliding Window Code With a Window Larger Than the List?

Yes. You should test it. Code above returns None in Python and INT_MIN in C++ when k exceeds the list length. Without that check the Python code adds the entire list and returns a wrong answer.

What Should You Remember About the Sliding Window?

Sliding window technique replaces a repeated scan with one pass. Slide a window across the list and update only the difference. Drop the leaving item and add the arriving item.

Work drops from O(n times k) to O(n) in the sliding window algorithm. Spot it when a problem talks about items in a row. Then decide if the window is fixed or variable.

Key takeaways.

  • Sliding window technique updates only the leaving item and the arriving item.
  • Fixed window has one size and variable window follows a rule.
  • Brute force takes O(n times k) time and sliding window takes O(n) time.

Practice question. In [1, 4, 2, 10, 2] find the largest sum of 2 neighbouring numbers. Answer. 12, from 2 plus 10.

Open the sliding window lesson for the reference and solve the sliding window practice problems.