Sliding Window
The Sliding Window Pattern
A window defined by a left and right index moves across the data. The right edge extends to include new elements; the left edge advances only when the window breaks a constraint. Running totals update incrementally rather than being recomputed, so each element is visited a constant number of times.
Interactive problems
Free to open
How do you recognise a sliding window problem?
The problem asks for the longest, shortest, or best contiguous subarray or substring satisfying a condition. The word "contiguous" is the tell, as is a fixed window size k. "Longest substring without repeating characters" and "maximum sum subarray of size k" are the canonical forms.
What is the time complexity of the sliding window pattern?
O(n) time — each index enters and leaves the window at most once — against O(n²) or O(n³) for recomputing every subarray.
Sliding Window practice problems
Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.
Sliding Window problems by difficulty and complexity
The difficulty, running time and extra space of every sliding window solution on this page, as each lesson derives them.
| Lesson | Difficulty | Best | Average | Worst | Space |
|---|---|---|---|---|---|
| Introduction to Sliding Window | Medium | Ω(n) | Θ(n) | O(n) | O(min(n, charset)) |
| Longest Substring Without Repeating Characters | Medium | Ω(n) | Θ(n) | O(n) | O(min(n, charset)) |
| Longest Repeating Character Replacement | Medium | Ω(n) | Θ(n) | O(n) | O(1) |
| Minimum Window Substring | Hard | Ω(|s| + |t|) | Θ(|s| + |t|) | O(|s| + |t|) | O(k) |
| Overview (Fixed Length) | Medium | Ω(n) | Θ(n) | O(n) | O(1) |
| Maximum Points You Can Obtain from Cards | Medium | Ω(k) | Θ(k) | O(k) | O(1) |
| Maximum Sum of Distinct Subarrays With Length K | Medium | Ω(n) | Θ(n) | O(n) | O(k) |
| Sliding Window Maximum | Hard | Ω(n) | Θ(n) | O(n) | O(k) |
Related patterns and concepts
The underlying technique is covered from first principles in the sliding window lesson in the DSA visualizer curriculum. Sliding Window is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.
Every other coding interview pattern
Depth-First Search · 25 lessons
- Introduction to DFSFree
- DFS FundamentalsFree
- Return Values in DFS
- Invert Binary Tree
- Maximum Depth of Binary Tree
- Path Sum
- Passing Values Down (State)
- Validate Binary Search Tree
- Kth Smallest Element in a BST
- Construct Binary Tree from Preorder and Inorder Traversal
- Binary Tree Tilt
- Diameter of Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Path Sum II
- Longest Univalue Path
- Graphs Overview
- Graph Representation: Adjacency List
- Clone Graph
- Graph Valid Tree
- Matrices as Graphs
- Flood Fill
- Types of DFS (Tree Traversals)
- Number of Islands
- Surrounded Regions
- Pacific Atlantic Water FlowFree
