Skip to content
Guest
Learn DSA · Course Syllabus Show lessons
Complexity & Patterns · 9 min read · Intermediate

Sliding Window Pattern

Solve contiguous subarray and substring problems in O(n) by expanding a right pointer and shrinking a left pointer.

What you'll learn

  • Recognize contiguous subarray/substring clues that call for Sliding Window
  • Maintain a running window sum or character frequency map in O(n) total time
  • Shrink the left pointer cleanly whenever the window violates a constraint

Whenever a problem asks for the longest/shortest/maximum contiguous subarray or substring, avoid recomputing each window from scratch in $O(n^2)$. A Sliding Window moves right forward to add an element and left forward to remove an element, visiting each item at most twice -> $O(n)$ time.

Fill-in-the-Blank Exercise

Fixed-Size Sliding Window

Update the running window sum by adding nums[i] and subtracting the outgoing element.

windowSum += nums[i] - nums[i - ];
best = Math.(best, windowSum);

Live DSA Playground

Longest Substring Without Repeating Characters
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. Why does a variable-size Sliding Window with an inner while-loop still run in O(n) total time?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind