Browse curriculum

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.

8

Interactive problems

2

Free to open

Recognise

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.

Complexity

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.

Problems

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++.

Complexity

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.

LessonDifficultyBestAverageWorstSpace
Introduction to Sliding WindowMediumΩ(n)Θ(n)O(n)O(min(n, charset))
Longest Substring Without Repeating CharactersMediumΩ(n)Θ(n)O(n)O(min(n, charset))
Longest Repeating Character ReplacementMediumΩ(n)Θ(n)O(n)O(1)
Minimum Window SubstringHardΩ(|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 CardsMediumΩ(k)Θ(k)O(k)O(1)
Maximum Sum of Distinct Subarrays With Length KMediumΩ(n)Θ(n)O(n)O(k)
Sliding Window MaximumHardΩ(n)Θ(n)O(n)O(k)
Curriculum

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.

Directory

Every other coding interview pattern