DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk6 min

Sliding Window Technique: Solve Subarray and Substring Problems Efficiently

Sliding windows update a contiguous range as its boundaries move. Learn the fixed-width and variable-width patterns, choose the right state, and check when the method’s assumptions hold.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The sliding window technique solves many contiguous subarray and substring problems by updating a range’s state as its boundaries move, instead of recalculating every range from scratch. Use a fixed-width window when the length is given; use a variable-width window when a constraint determines how far the range can grow or must shrink. The key test is whether the problem’s condition supports that movement.

What is a sliding window?

A window is a contiguous range in an array or string, bounded by left and right indices. As the right edge advances, the entering item is added to the state you maintain. If the left edge advances, the departing item is removed. The state might be a sum, a character-frequency table, or a data structure that tracks an extreme value.

As an Amazon Associate I earn from qualifying purchases.

This avoids recomputing overlapping ranges when their state can be updated more cheaply than it can be rebuilt. The usual linear-time guarantee is amortized: if both pointers only move forward, each item enters at most once and leaves at most once. With constant-time updates, the total work is O(n), even when the code contains a nested while loop.

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

This pattern is specifically for contiguous ranges. A two-pointer method that starts at opposite ends and moves inward is related, but it is not the same window pattern.

Choose between fixed and variable windows

Pattern When to use it How the boundaries move Typical state and cost
Fixed width The range length, such as k, is specified. Both boundaries advance together by one position per shift. A running sum supports constant-time updates. Extrema need a monotone deque; medians generally require ordered state and O(log k) updates.
Variable width The goal is a longest or shortest contiguous range satisfying a condition. Advance the right edge to include items; move the left edge as needed to restore validity. State depends on the condition: for example, a sum, frequency counts, or last-seen positions. Cost depends on how that state is updated.

How to solve a fixed-width window problem

Example: maximum sum of k consecutive elements

Recomputing the sum of every length-k range takes O(k) work per range, or O(nk) overall. A rolling sum takes constant time per shift.

  1. Decide the required behavior when k is not a valid width for the input. Reject it, return a designated result, or follow the problem’s stated rules.
  2. Compute the sum of the first complete window and use it to initialize the best sum.
  3. For each next position, update the sum with new_sum = old_sum + entering_value - leaving_value.
  4. Compare each updated sum with the best value, or emit the value if the task asks for every window’s sum.

For example, with values [2, 5, 1, 3] and k = 3, the first sum is 8. The next window adds 3 and removes 2, giving 9. Only the entering and departing values need to be processed for that shift.

Rank #2
Sale
Introduction to Algorithms, fourth edition
  • color: White
  • INTRODUCTION TO ALGORITHMS, FOURTH EDITION

When the fixed-width state is not a sum

A running sum cannot by itself maintain a rolling maximum or minimum: the outgoing item may have been the previous extreme. A monotone deque of candidate indices supports fixed-window extrema in linear total time. For a median, the state must preserve ordering; ordered structures generally cost O(log k) per update rather than constant time.

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

How to solve a variable-width window problem

Example: longest substring without repeated characters

Maintain the most recent index for each character. When the right edge reaches a character whose previous occurrence lies inside the current window, move the left edge to one position after that occurrence. Then record the largest window length seen.

For instance, in abca, the second a repeats a character still inside the window. Move the left boundary past the earlier a; do not move it backward if the recorded last-seen index is already outside the current window. This keeps the window valid while the right edge continues forward.

Example: longest repeating character replacement

For the uppercase-letter version of this problem, track character frequencies in the window. A window is valid when its size is no greater than the most frequent character count plus the allowed number of replacements, k. If it becomes invalid, advance the left edge and update the state as required by the chosen implementation. The uppercase alphabet in this example permits a 26-entry array; arbitrary Unicode or an unbounded character set needs a representation suited to that input.

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

Record the answer at the right time

For a longest valid window, expand the right edge and shrink until the window is valid, then compare its length with the best answer. For a shortest valid window, record a valid candidate before shrinking it further to look for a shorter one. The ordering depends on the objective and validity condition; a template should not decide it for you.

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

Which state should you maintain?

  • Running sum: Useful for sum constraints when values and the condition make the window’s behavior predictable.
  • Frequency map or array: Useful for distinct-character counts, anagrams, and other frequency constraints. A fixed-size array can use constant space for a fixed alphabet; a map’s size can grow with the number of distinct values in the active window.
  • Last-seen positions: Useful when a repeated item lets you jump the left boundary directly past its previous occurrence.
  • Monotone deque: Useful for maintaining a fixed-window minimum or maximum without rescanning the whole window.
  • Ordered structure: Useful for medians and other order-sensitive statistics, with extra update cost—typically O(log k) for median maintenance.

Choose the smallest state that lets you test the window’s condition and update it correctly when items enter or leave.

Best Value
Sale
Data Structures and Algorithms in Python
  • Used Book in Good Condition
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check whether the condition really supports a sliding window

The familiar variable-window rule for finding the longest subarray with sum at most S relies on non-negative values. Adding a value cannot lower the sum, and removing a value from the left cannot raise it. That predictable behavior makes it possible to move the left boundary whenever the sum exceeds the limit.

Negative values break that reasoning: extending a range can decrease its sum, while shrinking it can increase the sum. The usual greedy boundary movement may therefore skip valid answers. Use a different method, such as prefix sums with an appropriate lookup structure, when the exact problem and objective call for it. Calling a problem a “sliding window” problem is not enough to establish that the standard two-pointer rule is correct.

Understand the time and space costs

  • Time: With forward-only pointers and constant-time state updates, the total pass is O(n). The left pointer may move many times in one iteration, but it advances at most n times over the whole run. ETH Zürich’s 2025 exercise handout gives a maximum of 2n pointer increments for its non-negative subarray-sum method: ETH Zürich exercise handout.
  • State updates: If an update costs O(log n), the overall cost can be O(n log n) rather than O(n). The complexity follows from the update operation, not the technique’s name.
  • Space: The amount depends on the maintained state. A fixed-alphabet array can be constant-sized; a frequency map or ordered structure uses space based on the active values or items.

Practice in a useful order

  1. Start with fixed-width sums, including maximum sum over k consecutive values.
  2. Try longest substring without repeated characters, using last-seen positions.
  3. Practice a variable-width frequency constraint, then a fixed-window minimum or maximum using a deque.
  4. Test edge cases: empty and one-element inputs, k = 1, k equal to the input length, repeated values, a constraint that never becomes valid, and negative values where applicable.

For another explanation of the window definition and the uppercase-letter replacement example, see the UCSD Competitive Programming Club’s Week 5 — Two Pointers lesson. The AlgoWiki sliding-window guide also discusses window state, variants, and complexity.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.