Sliding Window

In short: The sliding window technique solves problems about contiguous subarrays or substrings by sliding a range (the window) across the input and updating the answer as items enter on the right and leave on the left, instead of recomputing every range from scratch. Fixed-size windows move one step at a time, while variable-size windows grow on the right and shrink from the left whenever they break the problem's rule. Because each item enters and leaves the window at most once, it usually runs in O(n) time.

Quick reference

The sliding window technique solves problems about a contiguous run of items (a subarray or a substring) by keeping a "window" between a left index and a right index and sliding it across the input, updating the answer as items enter on the right and leave on the left instead of recomputing every range from scratch. It usually turns an O(n²) or O(nk) brute-force solution into an O(n) one.

When to use it:

  • The problem asks about a contiguous subarray or substring: the longest, shortest, or maximum-sum one, or every run of k items in a row.
  • You can update what you know about the window (a sum, a count of each character, a set of what's inside) in O(1) time when one item enters or leaves it.

Two kinds of windows:

  • Fixed-size: the window always holds k items. Each step, one item enters on the right and one leaves on the left.
  • Variable-size: the window grows on the right, and shrinks from the left whenever it breaks the problem's rule.

Cost:

  • O(n) time, because each item enters the window once and leaves it at most once. Extra space is O(1) for a running sum, or the size of whatever hash map or set describes the window.

When to Use a Sliding Window

Reach for a sliding window when a problem about an array or a string has these signals:

  • It's about items that are next to each other: "subarray," "substring," "consecutive," "in a row," or "a window of size k."
  • It asks for the longest or shortest range that meets a condition, the maximum or minimum sum or average of a range, or the number of ranges that qualify.
  • The brute-force solution looks at every range, and neighboring ranges overlap almost completely, so most of that work gets repeated.

There's one more requirement, and it's the one people forget: the condition has to change predictably as the window grows and shrinks. For "longest substring without repeating characters," if a window has no repeats, every smaller window inside it has no repeats either. So shrinking a window can only help, and growing it can only hurt. That's what lets us move each edge in one direction only and never back up.

If the problem lets you pick items that aren't next to each other (a subsequence or a subset), a sliding window is the wrong tool. See common mistakes below.

Fixed-Size Sliding Window

Example problem: find the maximum sum of k consecutive numbers.

Take [2, 1, 5, 1, 3, 2] with k = 3. The brute-force approach adds up every group of 3 from scratch. That's k additions for each of the n - k + 1 windows, which is O(nk) time.

But look at two neighboring windows: [2, 1, 5] and [1, 5, 1]. They share 1 and 5. Moving the window one step to the right just adds the number that enters on the right and subtracts the number that leaves on the left:

Window (indexes) Numbers Change Window sum Best so far
0 to 2 2, 1, 5 Add up the first window 8 8
1 to 3 1, 5, 1 +1 enters, −2 leaves 8 + 1 − 2 = 7 8
2 to 4 5, 1, 3 +3 enters, −1 leaves 7 + 3 − 1 = 9 9
3 to 5 1, 3, 2 +2 enters, −5 leaves 9 + 2 − 5 = 6 9

The answer is 9, from [5, 1, 3]. Each step costs O(1) instead of O(k), so the whole thing takes O(n) time and O(1) extra space:

public static int maxWindowSum(int[] nums, int k) { if (k <= 0 || k > nums.length) { throw new IllegalArgumentException("k must be between 1 and the number of items"); } // add up the first window: nums[0] through nums[k - 1] int windowSum = 0; for (int i = 0; i < k; i++) { windowSum += nums[i]; } int bestSum = windowSum; // slide the window one step at a time for (int right = k; right < nums.length; right++) { windowSum += nums[right]; // the new number enters on the right windowSum -= nums[right - k]; // the oldest number leaves on the left bestSum = Math.max(bestSum, windowSum); } return bestSum; } // maxWindowSum(new int[] {2, 1, 5, 1, 3, 2}, 3) returns 9

The same shape works for any fixed-size question where you can add one item and remove one item in O(1): the average of every k numbers in a row, or whether a string contains an anagram of a k-letter word (keep a count of each letter in the window and compare it to the word's counts).

Variable-Size Sliding Window

When the problem asks for the longest or shortest range that meets a condition, the window's size isn't known up front. So we let it grow on the right, one item at a time, and shrink it from the left whenever it breaks the rule.

Example problem: find the length of the longest substring without repeating characters.

For "pwwkew," the answer is 3 ("wke"). "pwke" doesn't count: it skips the second w, so it's a subsequence, not a substring.

Checking every substring for repeats takes O(n³) time. Here's the sliding window instead. The right edge moves forward one character per step. If the new character is already in the window, the left edge moves forward until the earlier copy is gone:

Right edge New character Repeat? Left edge Window Longest so far
0 p No 0 p 1
1 w No 0 pw 2
2 w Yes: drop p, then the first w 0 → 2 w 2
3 k No 2 wk 2
4 e No 2 wke 3
5 w Yes: drop the w at index 2 2 → 3 kew 3

The window never moves backward. After each step it holds the longest substring without repeats that ends at the right edge, so the biggest window we ever see is the answer.

Want to try it yourself? Our practice question Longest Substring Without Repeating Characters walks through this problem from brute force to a version that moves the left edge in one jump.

The Sliding Window Template

Most variable-size sliding window solutions follow the same three steps for each new item: grow, shrink, record. Here's the template for "find the longest window that follows a rule," and the slightly different one for "find the shortest window that reaches a goal":

# Longest window that follows a rule left = 0 for right from 0 to n - 1: add items[right] to the window # 1. grow while the window breaks the rule: # 2. shrink remove items[left] from the window left = left + 1 best = max(best, right - left + 1) # 3. record # Shortest window that reaches a goal left = 0 for right from 0 to n - 1: add items[right] to the window # 1. grow while the window reaches the goal: best = min(best, right - left + 1) # 3. record remove items[left] from the window # 2. shrink left = left + 1

Here's the "longest" template filled in for the longest substring without repeating characters. The window's state is a hash map counting how many times each character appears, and the rule is "no character appears more than once":

import java.util.HashMap; import java.util.Map; public static int longestUniqueSubstring(String s) { Map<Character, Integer> counts = new HashMap<>(); // how many times each character appears in the window int left = 0; // the window is s[left..right] int longest = 0; for (int right = 0; right < s.length(); right++) { // 1. grow: add the next character on the right char c = s.charAt(right); counts.put(c, counts.getOrDefault(c, 0) + 1); // 2. shrink: while the window breaks the rule (c repeats), // remove characters from the left while (counts.get(c) > 1) { char leftChar = s.charAt(left); counts.put(leftChar, counts.get(leftChar) - 1); left++; } // 3. record: the window has no repeats now, so check its length longest = Math.max(longest, right - left + 1); } return longest; } // longestUniqueSubstring("pwwkew") returns 3, for "wke"

To adapt it, change two things: what you track about the window (a sum, counts, a set) and when the window is invalid. For the longest substring with at most k distinct characters, for example, shrink while the counts have more than k nonzero entries.

Sliding Window Time and Space Complexity

A variable-size window has a while loop inside a for loop, so it can look like O(n²). It isn't. The right edge moves forward n times in total, and the left edge only ever moves forward, so it moves at most n times in total too. Each item enters the window once and leaves it at most once, which is 2n steps of O(1) work: O(n) time.

Space depends on what you keep about the window: a running sum is O(1), and a set or count of characters is O(min(n, m)), where m is the number of different characters that can show up.

Problem Brute force Sliding window
Maximum sum of k consecutive numbers O(nk) time O(n) time, O(1) space
Longest substring without repeating characters O(n³) time checking every substring, or O(n²) if you grow each start with a set O(n) time, O(min(n, m)) space

You can't beat O(n) time on these problems, since any item you skip could change the answer. For more on how to count steps like this, see our big O notation guide.

Sliding Window vs. Two Pointers

A sliding window is a special kind of two pointers technique. The difference is which way the pointers move and what's between them:

Sliding window Two pointers (opposite ends)
How the pointers move Both move in the same direction, left to right, and the left one never passes the right one Start at the two ends and move toward each other
What matters Everything between the pointers (the window) Usually just the two items the pointers are on
What you keep track of A running summary of the window: a sum, counts, or a set Often nothing beyond the two indexes
Typical input Any array or string (doesn't need to be sorted) Often a sorted array, or anything you're reversing or checking from both ends
Typical problems Longest substring without repeating characters, maximum sum of k in a row, minimum window substring Pair with a target sum in a sorted array, reversing a string in place, palindrome checks
Time O(n) O(n), plus O(n log n) if you have to sort first

Other two-pointer patterns include a fast and a slow pointer on a linked list (as in detecting a cycle) and one pointer in each of two sorted arrays (as in merging sorted arrays). If the problem cares about the contents of a contiguous range, it's a sliding window.

Common Sliding Window Mistakes

  • Using it when the items don't have to be contiguous. "Longest increasing subsequence" and "pick any k numbers with the biggest sum" let you skip items, so there's no window to slide. Those call for dynamic programming or simply choosing the k largest numbers.

  • Sum limits with negative numbers. "Shrink the window while the sum is too big" only works when every number is zero or positive, so adding an item never lowers the sum and removing one never raises it. With negatives, that breaks. Take the longest subarray of [4, −3, 1] with a sum of at most 2. The window sees 4, decides the sum is too big, and drops the 4 for good. It ends up answering 2 (for [−3, 1]), but the whole array sums to 2, so the right answer is 3. Problems like this need prefix sums instead (often with a hash map, or a monotonic deque).

  • Off-by-one window length. If left and right are both inside the window, its length is right - left + 1, not right - left.

  • Forgetting to update the state when the left edge moves. Every item that leaves the window has to come out of your sum, set, or counts. If you count distinct characters with a map's size, delete a character's entry when its count drops to zero.

  • Recording the answer at the wrong time. For the longest window, record it after shrinking, once the window is valid again. For the shortest window, record it inside the shrinking loop, while the window still meets the goal.

  • Moving the left edge backward. A common speedup jumps the left edge just past the last place we saw the repeated item. If that spot is before the window (in "abba," the second a's earlier copy is already gone by the time we reach it), jumping there would move the left edge backward and let a repeat back in. Only jump forward.

Classic Sliding Window Problems

Fixed-size windows:

  • Maximum (or average) of k consecutive numbers. Keep a running sum.
  • Find all anagrams of a word in a string (or check whether a string contains a permutation of another). Slide a window as long as the word and compare letter counts.
  • Sliding window maximum (the largest number in every window of size k). Keep a monotonic deque of indexes whose values decrease from front to back, so the front is always the window's maximum.

Variable-size windows:

  • Longest substring without repeating characters. Shrink while the new character is already in the window. Practice it: Longest Substring Without Repeating Characters.
  • Longest substring with at most k distinct characters. Shrink while the window has more than k distinct characters.
  • Longest run of 1s if you can flip at most k 0s. Shrink while the window holds more than k zeros.
  • Shortest subarray with a sum of at least a target (all numbers positive). Record and shrink while the sum is big enough.
  • Minimum window substring (the shortest substring that contains every character of another string). Record and shrink while the window still covers every needed character.

Sliding Window interview questions to practice

Each one walks you through a real coding interview problem one hint at a time.

Your first 3 questions are free. Just sign in, no credit card.

Frequently Asked Questions

What is the sliding window technique?

It's a way to solve problems about contiguous subarrays or substrings by keeping a window between a left index and a right index and sliding it across the input. As the window moves, you update a running summary of it, like a sum or a count of each character, instead of recomputing every range from scratch.

When should you use a sliding window?

When a problem asks about items that are next to each other, like the longest substring with some property, the maximum sum of k consecutive numbers, or the shortest subarray that reaches a target, and you can update what you know about the window in constant time as one item enters or leaves.

What is the time complexity of the sliding window technique?

Usually O(n). Even with a while loop inside the for loop, the right edge moves forward n times and the left edge only moves forward, at most n times in total, so each item enters and leaves the window at most once.

What's the difference between a fixed-size and a variable-size sliding window?

A fixed-size window always holds k items, so each step adds one item on the right and removes one on the left. A variable-size window grows on the right and shrinks from the left whenever it breaks the problem's rule, which is how you find the longest or shortest range that works.

What's the difference between sliding window and two pointers?

A sliding window is a kind of two-pointer technique where both pointers move in the same direction and everything between them matters. Other two-pointer techniques often start at opposite ends of a sorted array and move toward each other, looking only at the two items the pointers are on.

When doesn't a sliding window work?

When the items you need don't have to be next to each other, like subsequences or subsets, or when growing and shrinking the window doesn't change whether it's valid in a predictable way, like a sum limit on an array with negative numbers. Those problems usually need dynamic programming or prefix sums instead.

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

. . .