Sliding Window

DSA · Arrays and Searching

Theory

A sliding window keeps a contiguous range of elements and moves it across the array, adding the element that enters on the right and removing the one that leaves on the left. Instead of recomputing each window from scratch, it updates a running value, so the total work is O(n). Windows can have a fixed size (average of every k days) or a variable size that grows and shrinks to satisfy a condition.

Why we use it

It turns repeated work over overlapping ranges into a single linear pass.

When to use it

Use it for subarray or substring problems: maximum sum of k items, longest substring without repeats, smallest window meeting a total, moving averages.

How it works

  1. Start: left = 0, window empty
  2. For right = 0..n-1: add arr[right] to window
  3. Window breaks the rule (too big / invalid)? Yes: Remove arr[left], left = left + 1, check again. No: Update best answer.
  4. Return best answer after the last right

Syntax

Fixed window of size k:
  window = sum(arr[:k])
  for i in range(k, n):
      window += arr[i] - arr[i-k]

Variable window:
  for right in range(n):
      add arr[right]
      while window invalid: remove arr[left]; left += 1

Example

def max_sum_k(nums, k):
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]
        best = max(best, window)
    return best

def longest_unique(s):
    seen = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in seen and seen[ch] >= left:
            left = seen[ch] + 1
        seen[ch] = right
        best = max(best, right - left + 1)
    return best

print("Best 3-day sales:", max_sum_k([120, 80, 150, 90, 200, 60], 3))
print("Longest unique substring:", longest_unique("abcabcbb"))

Key points

DSA topics

Introduction to DSA

Arrays and Searching

Sorting Algorithms

Linked Lists

Stacks and Queues

Hashing

Trees

Heaps

Graphs

Algorithm Techniques

Classic Algorithms

Dynamic Programming

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Data Structures & Algorithms

The complete DSA roadmap: theory, why and when to use every structure and algorithm, Big O complexity, and Python code you can run right here in the browser.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice DSA Online 251 problems across 13 patterns, with hidden tests and step-by-step optimal solutions. Start practising →
Section {{ sec.num }}

{{ sec.label }}

DSA  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ current.why }}

When to use it

{{ current.when }}

Flowchart — how {{ current.name }} works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Step-by-step visualisation
{{ cell.v }}
{{ cell.i }} {{ cell.tag }}
Step {{ vizStepLabel }}: {{ vizNote }}
■ comparing ■ swapping / moving ■ done / found ■ out of range
Complexity & Pseudocode
{{ current.syntax }}
Example Code
{{ current.example }}
▶ Try It Live — runs real Python 3 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic