What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

The sliding window technique solves many contiguous subarray and substring problems by maintaining a range of input and updating its state as the range moves. Use a fixed-width window when the length is given; use a variable-width window when a validity condition determines how far the boundaries move. The method is often O(n), but only when its state can be updated efficiently and the problem’s constraints justify the movement rule.

What is a sliding window?

A window is a contiguous range bounded by a left index and a right index. It can represent a subarray in an array or a substring in a string. Instead of calculating each candidate range from scratch, maintain the information needed for the current range. When the right boundary advances, incorporate the entering item; when the left boundary advances, remove the departing item or update the state to reflect that it is no longer included.

This helps when neighboring ranges overlap and updating their shared state costs less than recomputing it. Sliding windows apply to contiguous ranges; a two-pointer method that starts at opposite ends and moves inward is related, but it is not the same pattern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to recognize when to use it

Look for a problem about a contiguous range and ask whether adjacent candidate ranges share most of their elements. Typical clues include a fixed number of consecutive elements, the longest or shortest range satisfying a condition, or a substring with a character constraint.

  • Maximum sum of k consecutive elements: the width is fixed, so update a running sum as the range shifts.
  • Longest substring without repeating characters: the width changes to preserve a uniqueness condition.
  • Window minimum or maximum: the range may be fixed, but maintaining its extreme requires more than a running sum.

The key question is not whether the statement mentions two indices. It is whether the range can move while its relevant state is updated correctly and cheaply.

Fixed-width windows

Use a fixed-width window when the problem specifies a length such as k. For a sum, calculate the first complete window, then shift it one position at a time with new_sum = old_sum + entering_value - leaving_value. This takes constant work per shift after initialization.

Example: maximum sum of k consecutive values

For input [2, 1, 5, 1, 3, 2] and k = 3, the first sum is 2 + 1 + 5 = 8. Shift right: add 1 and subtract the departing 2, giving 7. Shift again: add 3 and subtract 1, giving 9. The last shift adds 2 and subtracts 5, giving 6. The maximum is 9.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Introduction to Algorithms, fourth edition
  • color: White
  • INTRODUCTION TO ALGORITHMS, FOURTH EDITION

Recomputing each length-k sum uses up to k additions per position. The rolling update avoids that repeated work. Decide explicitly what the implementation should do when k is less than one or greater than the input length; the right behavior depends on the problem specification.

When the state is not a sum

A running sum does not maintain a rolling maximum or minimum: the departing value may have been the extreme, and the sum does not reveal the next one. A monotone deque of candidate indices can maintain a fixed-window minimum or maximum in linear total time. A rolling median generally requires ordered state, such as an ordered multiset, and can take O(log k) per update.

Variable-width windows

Use a variable-width window when the range expands and contracts according to a condition. Advance the right boundary to include new input and update the state. If the window violates the condition, advance the left boundary until the required invariant is restored.

The point at which you record an answer depends on the objective. To maximize the length of a valid range, record after shrinking until the window is valid. To minimize a range that meets a condition, record while it is valid before shrinking it further. Keep the invariant and the recording point explicit in the implementation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example: longest substring without repeating characters

Maintain the most recent index for each character. If the character at the right boundary was last seen inside the current window, move the left boundary to one position after that earlier occurrence. Then update the character’s last-seen index and compare the current window length with the best found so far.

For example, in abcabcbb, the repeated a forces the left boundary past its previous occurrence. The boundary must never move backward: an old occurrence outside the current window does not make the current window invalid.

Rank #4
Sale
Data Structures and Algorithms Made Easy: Data Structures and Algorithmic Puzzles
  • Binding: paperback
  • Language: english
  • It ensures you get the best usage for a longer period

Example: longest substring after replacing up to k characters

For the uppercase-letter example in the UCSD Competitive Programming Club’s Week 5 — Two Pointers slides, maintain character frequencies and the highest frequency in the window. The window is valid when window size <= highest frequency + k: all but the most frequent character could be replaced within the allowance. The slides use uppercase letters; a 26-entry frequency array fits that defined alphabet, not arbitrary Unicode text or an unbounded character set.

Choose state that matches the condition

The window’s maintained state should be just enough to test validity or evaluate the objective. State choice determines both correctness and cost.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Problem state Useful representation Important qualification
Sum threshold with non-negative values Running sum The usual grow-right, shrink-left rule depends on non-negative values.
Character frequencies, distinct count, or anagram counts Frequency array or map An array is constant-sized only for a fixed, bounded alphabet; a map can grow with distinct values in the window.
Duplicate detection in a substring Last-seen indices Advance the left boundary only when the earlier index is within the current window.
Window minimum or maximum Monotone deque of indices Each index enters and leaves at most once over the full pass.
Window median or other order-sensitive statistic Ordered structure Updates generally add logarithmic cost rather than constant-time cost.

Check the monotonicity assumption

The familiar variable-window rule for finding the longest subarray whose sum is at most a target works when values are non-negative. Extending the window cannot lower its sum, and removing a value from the left cannot raise it. Those properties let the boundaries move predictably.

Best Value
Sale
Data Structures and Algorithms in Python
  • Used Book in Good Condition

With negative values, either movement can change the sum in the opposite direction. A greedy shrink-or-expand rule may then skip valid ranges, so the standard template is not justified. Consider a different method, such as prefix sums with an appropriate lookup structure, if it fits the precise objective. Calling a problem a “sliding window” problem does not establish that the usual two-pointer rule is correct.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why the common pattern is linear—and when it is not

When both boundaries only move forward, each input element enters at most once and leaves at most once. If each state update takes constant time, total work is O(n). A nested while loop does not by itself make the algorithm quadratic: the left boundary can advance at most n times across the whole run. ETH Zürich’s 2025 exercise handout bounds its non-negative subarray-sum method at a maximum of 2n pointer increments.

The bound depends on the update cost. A deque-based extrema method can still do linear total work because each index is added to and removed from the deque at most once. If each update requires an ordered structure, the total may instead be O(n log k). Space depends on the state: a frequency map uses space proportional to the distinct values it stores, while a fixed-alphabet array has fixed size.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical implementation checklist

  1. Confirm contiguity. The range must consist of consecutive array elements or string characters.
  2. Choose the pattern. Use fixed width for a given length; use variable width when a validity condition controls expansion and contraction.
  3. State the invariant. Define what the current window must represent or satisfy.
  4. Select sufficient state. Use a sum, frequency structure, last-seen positions, deque, or ordered structure as the task requires.
  5. Specify boundary behavior. Define what happens for empty input, invalid widths, or a condition that no range can satisfy.
  6. Check the assumptions. In particular, verify whether values are non-negative before using a greedy sum-threshold window.
  7. Test edge cases. Try empty and one-element inputs, k = 1, k equal to the input length, repeated values, and relevant negative values.

Suggested practice sequence

Build the ideas in stages: start with fixed-width sums, then solve longest substring without repeated characters, then try a distinct-count constraint, and finally implement a deque-based sliding minimum. Each step changes the maintained state or the boundary rule while preserving the central idea: update a contiguous range rather than rebuild it.

Quick Recap

SaleBestseller No. 2
Introduction to Algorithms, fourth edition
Introduction to Algorithms, fourth edition
color: White; INTRODUCTION TO ALGORITHMS, FOURTH EDITION
$99.47
SaleBestseller No. 4
Data Structures and Algorithms Made Easy: Data Structures and Algorithmic Puzzles
Data Structures and Algorithms Made Easy: Data Structures and Algorithmic Puzzles
Binding: paperback; Language: english; It ensures you get the best usage for a longer period
$29.41
SaleBestseller No. 5
Data Structures and Algorithms in Python
Data Structures and Algorithms in Python
Used Book in Good Condition
$125.13

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.