The sliding window idea
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)When a problem asks for the best contiguous subarray or substring, a brute-force solution recomputes the sum or character count of every window from scratch in O(n · k) or O(n²) time. The sliding window pattern notices that two adjacent windows share almost all of their elements, letting you update the window in O(1) per step.
Subarray and substring questions
A sliding window is a range of consecutive elements that moves across an array or string, adding one element on the right and removing one on the left, to avoid recomputing from scratch.
A subarray (or substring) is a contiguous slice nums[left .. right] with no gaps between indices. An array of length n has (n(n+1))/2 = O(n²) non-empty subarrays. A subsequence is different: it allows skipping elements (while keeping left-to-right order) and has 2ⁿ possibilities.
import java.util.Arrays;
public class AllSubarrays { public static void main(String[] args) { int[] nums = {4, 7, 1}; for (int left = 0; left < nums.length; left++) { for (int right = left; right < nums.length; right++) { System.out.println(Arrays.toString(Arrays.copyOfRange(nums, left, right + 1))); } } }}[4] [4, 7] [4, 7, 1] [7] [7, 1] [1]
The sliding window pattern applies specifically to contiguous subarrays and substrings where you can maintain a summary of the current range [left .. right] (such as its sum, vowel count, or character frequencies) as left and right move forward.
- Keywords that signal a window: contiguous subarray, substring, k consecutive elements, longest/shortest range with....
- Window length formula: the number of elements in
[left .. right](inclusive) is alwaysright - left + 1. - Amortized O(n) time: both
leftandrightstart at0and only move right, so each element enters the window once and leaves at most once.
Reusing the previous window instead of starting over
Take nums = [2, 1, 5, 1, 3, 2] and k = 3. Each window's sum shares most of its numbers with the window before it.
- Identify the state you need to maintain for the current window (sum, count, map).
- Define how the state changes when
nums[right]enters the window. - Define how the state changes when
nums[left]leaves the window. - Update the answer whenever the window is valid.
Sliding a window of size 3 over [2, 1, 5, 1, 3, 2]
Step 1 of 4
- sum
- 8
- 8
Example 1 · Brute force: add up every window from scratch (O(n · k) time, O(1) extra space)
import java.util.Arrays;
public class WindowSumsBrute { public static int[] windowSumsBruteForce(int[] nums, int k) { int[] sums = new int[nums.length - k + 1]; for (int i = 0; i <= nums.length - k; i++) { int sum = 0; for (int j = i; j < i + k; j++) { sum += nums[j]; } sums[i] = sum; } return sums; }
public static void main(String[] args) { int[] nums = {2, 1, 5, 1, 3, 2}; System.out.println("Brute force: " + Arrays.toString(windowSumsBruteForce(nums, 3))); }}Brute force: [8, 7, 9, 6]
What this code does
- There are
n - k + 1windows, and each one addsknumbers again, so the work is about n × k additions. - Neighbouring windows share
k - 1numbers. Adding them again is the repeated work the sliding window removes.
Example 2 · Optimal: slide the window, add the new value and drop the old one (O(n) time, O(1) extra space)
import java.util.Arrays;
public class WindowIdeaDemo { public static int[] windowSumsSliding(int[] nums, int k) { int[] sums = new int[nums.length - k + 1]; int windowSum = 0; for (int right = 0; right < nums.length; right++) { windowSum += nums[right]; if (right >= k - 1) { int left = right - k + 1; sums[left] = windowSum; windowSum -= nums[left]; } } return sums; }
public static void main(String[] args) { int[] nums = {2, 1, 5, 1, 3, 2}; System.out.println("Sliding window: " + Arrays.toString(windowSumsSliding(nums, 3))); }}Sliding window: [8, 7, 9, 6]
What this code does
- There are
n - k + 1 = 6 - 3 + 1 = 4windows of size 3 in an array of length 6. - Once
rightreaches indexk - 1(2), the window has size3, we recordwindowSum, and subtractnums[right - k + 1]before the next step. - Why it is faster: each step does one addition and one subtraction whatever k is, so the total is O(n) instead of O(n · k).
- Window 0 (
indices 0..2):2 + 1 + 5 = 8 - Window 1 (
indices 1..3):1 + 5 + 1 = 7
Notice that 1 + 5 is in both windows! Instead of adding k numbers again, Window 1 is simply:
newSum = oldSum + enteringElement - leavingElement = 8 + nums[3] - nums[0] = 8 + 1 - 2 = 7
Whether k = 3 or k = 50,000, sliding the window one step to the right takes just one addition and one subtraction (O(1) time), dropping total time from O(n · k) to O(n).
Predict the output
Slide the window
Work out the printed sum.
The window [2, 1, 5] has sum 8. What does this code print after one slide?
Fixed versus variable windows
Sliding window problems come in two flavors: a window of fixed size, and a window whose size changes.
Example 3 · Variable-size window: longest subarray with sum <= budget
public class VariableWindowIdeaDemo { // All elements in costs[] are positive public static int longestSubarrayWithinBudget(int[] costs, int budget) { int left = 0; int windowSum = 0; int maxLen = 0;
for (int right = 0; right < costs.length; right++) { windowSum += costs[right]; // Grow window on the right while (windowSum > budget) { // Shrink from the left until valid windowSum -= costs[left]; left++; } maxLen = Math.max(maxLen, right - left + 1); } return maxLen; }
public static void main(String[] args) { int[] costs = {3, 1, 2, 1, 4, 2}; System.out.println("Max items within budget 6: " + longestSubarrayWithinBudget(costs, 6)); }}Max items within budget 6: 3
What this code does
- At
right = 3(costs[1..3] = [1, 2, 1]),windowSumafter shrinkingcosts[0] = 3is4 <= 6, giving length3 - 1 + 1 = 3. - Each element is added once when
rightvisits it and subtracted at most once whenleftpasses it.
Example 4 · Counting total pointer operations to verify O(n) complexity
public class WindowComplexityProofDemo { public static void traceOperations(int[] nums, int limit) { int left = 0, sum = 0; int adds = 0, subtracts = 0; for (int right = 0; right < nums.length; right++) { sum += nums[right]; adds++; while (sum > limit) { sum -= nums[left++]; subtracts++; } } System.out.printf("n=%d -> adds=%d, subtracts=%d, total ops=%d (<= 2n)%n", nums.length, adds, subtracts, adds + subtracts); }
public static void main(String[] args) { traceOperations(new int[]{1, 1, 1, 1, 1, 10, 1, 1}, 5); }}n=8 -> adds=8, subtracts=6, total ops=14 (<= 2n)
What this code does
- Even when
nums[5] = 10forces the innerwhileloop to shrink 6 elements in a single step, those 6 elements can never be subtracted again. - Across all n = 8 outer iterations,
addsis 8 andsubtractsis 6 ≤ 8, proving the amortized O(1) per step (O(n) total) bound.
- Fixed-size window: The problem gives you an exact length k (for example, 'maximum sum of a subarray of size k' or 'all substrings of length k with no repeats'). Once the window reaches size k,
leftandrightadvance in lockstep soright - left + 1 == kon every step. - Variable-size window: The length is not fixed. Instead, the problem gives a validity condition (for example, 'longest substring with at most 2 distinct characters' or 'smallest subarray with sum ≥ S'). You grow the window by advancing
rightin aforloop, and whenever the condition is violated (or satisfied, for minimum-length problems), you shrink the window from the left with awhileloop (left++).
while loop inside the for loop is still O(n) total time because left++ can execute at most n times across the entire run!How to spot this pattern
Look for these clues in the problem statement.
- It asks about a contiguous subarray or substring, not a subsequence.
- It asks for the longest, shortest, maximum or count of ranges, often with a size k or a limit such as "at most k distinct".
- A summary of the range (sum, count, map of letters) can be updated when one element enters and one leaves.
- Fixed size k: slide a window of constant length. A condition on the range: grow on the right and shrink on the left.
Next step
Check your understanding
10 quick questions