Skip to content
We areTOP 1%
DSA · Intermediate · Pattern 1 of 10

Sliding Window

14 problems.
Your progress0%
1st Visit
0/14
2nd Visit
0/14
Revise
0/14

About this pattern

A sliding window maintains a contiguous range [l, r] and updates a summary of it (a sum, a frequency table, a count of distinct items) incrementally as the right end advances and the left end catches up. Fixed-size windows move both ends together; variable-size windows extend r and then shrink l until a condition is restored.

Signals: the statement asks for the longest, the shortest or the number of contiguous subarrays or substrings that satisfy a constraint, and the constraint stays valid when the window shrinks. Since each index enters and leaves the window once, the scan is O(n) plus the cost of updating the summary.

// Longest window whose condition can be restored by shrinking.
int best = 0;
unordered_map<char, int> cnt;              // window summary
for (int l = 0, r = 0; r < (int)s.size(); ++r) {
    cnt[s[r]]++;                           // extend right
    while (windowInvalid(cnt)) {           // shrink left until valid
        if (--cnt[s[l]] == 0) cnt.erase(s[l]);
        ++l;
    }
    best = max(best, r - l + 1);
}

Problems

Sliding Window questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Maximum Average Subarray ILeetCodeEasy Solve Maximum Average Subarray I on LeetCode (opens in a new tab)
2Lecture SleepCodeforcesEasy 1200Solve Lecture Sleep on Codeforces (opens in a new tab)
3Ternary StringCodeforcesEasy 1200Solve Ternary String on Codeforces (opens in a new tab)
4Binary DequeCodeforcesEasy 1200Solve Binary Deque on Codeforces (opens in a new tab)
5Longest Substring Without Repeating CharactersLeetCodeMedium Solve Longest Substring Without Repeating Characters on LeetCode (opens in a new tab)
6Permutation in StringLeetCodeMedium Solve Permutation in String on LeetCode (opens in a new tab)
7Max Consecutive Ones IIILeetCodeMedium Solve Max Consecutive Ones III on LeetCode (opens in a new tab)
8Fruit Into BasketsLeetCodeMedium Solve Fruit Into Baskets on LeetCode (opens in a new tab)
9Longest Repeating Character ReplacementLeetCodeMedium Solve Longest Repeating Character Replacement on LeetCode (opens in a new tab)
10Money TreesCodeforcesMedium 1300Solve Money Trees on Codeforces (opens in a new tab)
11BooksCodeforcesMedium 1400Solve Books on Codeforces (opens in a new tab)
12Vasya and StringCodeforcesMedium 1500Solve Vasya and String on Codeforces (opens in a new tab)
13Minimum Window SubstringLeetCodeHard Solve Minimum Window Substring on LeetCode (opens in a new tab)
14Sliding Window MaximumLeetCodeHard Solve Sliding Window Maximum on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account