Problem 239

Abstract / Summary

Given a list of numbers and a window size, output the maximum number in each sliding window.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0239.cpp

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        map<int, int> freq;
        for (int i = 0; i < k; i++)
            freq[nums[i]]++;

        vector<int> result;
        result.push_back(freq.rbegin()->first);

        for (int i = 1; i <= nums.size() - k; i++)
        {
            auto prev = nums[i - 1];
            auto next = nums[i - 1 + k];

            freq[prev]--;
            freq[next]++;

            auto top = freq.rbegin()->first;
            if (prev == top)
                while (!freq.empty() && freq[top] == 0)
                {
                    freq.erase(top);
                    top = freq.rbegin()->first;
                }

            result.push_back(top);
        }

        return result;
    }
};
32 lines | 812 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Heap (Priority Queue)
  • Monotonic Queue
  • Queue
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation computes the maximum value inside every contiguous sub-array (window) of length k for a given integer vector nums. It maintains a frequency map of the elements currently inside the window and extracts the largest key from the map after each slide. The result vector accumulates these maxima in order.

Initialization of the Frequency Map

At the start the code populates a std::map<int,int> named freq with the counts of the first k elements.

map<int, int> freq;
for (int i = 0; i < k; i++)
    freq[nums[i]]++;

Because std::map stores keys in sorted order, the greatest element of the window can be accessed via freq.rbegin()->first. This step also implicitly handles the case where k equals the size of nums; the loop iterates over the entire vector and the map reflects the whole input.

Recording the First Window Maximum

After the initial population, the algorithm records the maximum of the first window.

vector<int> result;
result.push_back(freq.rbegin()->first);

The use of rbegin() guarantees that the largest key is retrieved in constant time relative to the map’s internal structure.

Sliding the Window

The core loop moves the window one position to the right until the end of the array is reached. For each shift it identifies the element that leaves the window (prev) and the element that enters (next).

for (int i = 1; i <= nums.size() - k; i++)
{
    auto prev = nums[i - 1];
    auto next = nums[i - 1 + k];

The frequencies are updated by decrementing the count of prev and incrementing the count of next.

    freq[prev]--;
    freq[next]++;

Maintaining a Clean Maximum

The algorithm obtains the current maximum after the update.

    auto top = freq.rbegin()->first;

If the element that just left the window (prev) happens to be the current maximum, the map may now contain a zero count for that key. The code checks this condition and, while the map is non-empty and the top key has a zero frequency, it erases the entry and fetches the next largest key.

    if (prev == top)
        while (!freq.empty() && freq[top] == 0)
        {
            freq.erase(top);
            top = freq.rbegin()->first;
        }

This loop ensures that the map never returns a stale maximum and that zero-frequency entries are removed lazily, only when they could affect the result. It also gracefully handles the situation where multiple identical maximum values exist; only when the last occurrence leaves the window does the map advance to the next lower key.

Storing the Result for the Current Window

Finally, the verified maximum top is appended to the result vector.

    result.push_back(top);
}

When the loop terminates, result contains the maximum of every sliding window in the original order.

Edge Cases Handled

The code correctly processes an input where k is 1, because each iteration creates a frequency map with a single element and the maximum is that element itself.

When all elements in nums are identical, the map holds a single key with a count equal to k. Decrementing the count never removes the key until the window slides past the last occurrence, at which point the lazy removal loop cleans the map without affecting correctness.

If k equals the length of nums, the outer sliding loop does not execute because the condition i <= nums.size() - k evaluates to false after the first iteration, leaving the result vector with a single entry-the maximum of the whole array.

When the window contains a mixture of positive, negative, and zero values, the sorted nature of std::map still guarantees that rbegin() points to the numerically greatest key, irrespective of sign.

Performance Optimizations Observed

The choice of std::map provides ordered storage with logarithmic insertion and deletion. By keeping only frequency counts, the algorithm avoids storing duplicate entries, reducing the map’s size when many repeated values appear.

The retrieval of the maximum via rbegin() is an O(1) operation on the map iterator, eliminating the need for a full scan of the window.

Zero-frequency entries are not removed immediately after each decrement; instead, they are purged only when they could become the top element. This lazy deletion reduces the number of erase operations, especially in scenarios with many duplicate values where the maximum persists across several windows.

The loop that cleans up stale maximum entries stops as soon as a non-zero frequency is found, preventing unnecessary traversal of the map.

Overall, the algorithm balances the cost of maintaining order with the benefit of constant-time maximum extraction, resulting in an efficient sliding-window maximum computation for the given data structure.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of numbered cards lying on a table. A small window fits over a few of these cards at once, and it slides along the line from the left side to the right side. The goal is to see which card in that window has the biggest number written on it.

To do this, the code follows a simple plan. First, it fills a special container with all the numbers that fit inside the window when it starts at the beginning. This container acts like a tidy shelf that always keeps the biggest numbers at the very front. Looking at the front of this shelf gives the smartest answer for the first window.

Now the sliding begins. As the window moves one step to the right, one card leaves from the back and a new card enters at the front. The code takes the card that left the window off the shelf and adds the new card that just arrived. If the card that left happened to be the biggest one, the shelf cleans itself up by removing any empty spaces until it finds the new biggest number. After updating the shelf, the code writes down the biggest number it finds for that new position. This continues until the window has traveled across all the cards.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5 | μ = 5.00 | σ = 1.59

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Java Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
56 links | 39 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Sliding Window Maximum | Solution'
Pepcoding 22 mins
Sliding Window Maximum | Solution
YouTube video 'Sliding Window Maximum - Leetcode 239 | Monotonic Deque O(N) | Java & Python'
Code With K5KC 8 mins
Sliding Window Maximum - Leetcode 239 | Monotonic Deque O(N) | Java & Python
YouTube video 'LeetCode 239: Sliding Window Maximum'
Engineering Digest 17 mins
LeetCode 239: Sliding Window Maximum
YouTube video 'Sliding Window Maximum | Leetcode 239 | Hard'
Naresh Gupta 10 mins
Sliding Window Maximum | Leetcode 239 | Hard
YouTube video 'Sliding Window Maximum 🔥🔥 | Leetcode 239 | #Amazon | #Flipkart | #Directi | Hard |  C++'
Ayushi Sharma 20 mins
Sliding Window Maximum 🔥🔥 | Leetcode 239 | #Amazon | #Flipkart | #Directi | Hard | C++
YouTube video 'Sliding Window Maximum: 239 - sliding window technical interview question'
Destination FAANG 20 mins
Sliding Window Maximum: 239 - sliding window technical interview question
YouTube video 'Sliding window maximum | deque | queue | Java DSA Placement | FAANG | Leetcode'
ShashCode 30 mins
Sliding window maximum | deque | queue | Java DSA Placement | FAANG | Leetcode
YouTube video '239. Sliding Window Maximum II Monotonic Deque II Leetcode 239'
Aryan Mittal 22 mins
239. Sliding Window Maximum II Monotonic Deque II Leetcode 239
YouTube video '[Java] Deque | Solve Leetcode -  Sliding Window Maximum'
Eric Programming 15 mins
[Java] Deque | Solve Leetcode - Sliding Window Maximum
YouTube video 'Sliding Window Maximum: Efficient Deque Solution Explained | LeetCode 239 | Geekific'
Geekific 6 mins
Sliding Window Maximum: Efficient Deque Solution Explained | LeetCode 239 | Geekific
YouTube video 'Daily Leetcode #1233: Aug 16, 2023 - 239. Sliding Window Maximum'
Programming Live with Larry 16 mins
Daily Leetcode #1233: Aug 16, 2023 - 239. Sliding Window Maximum
YouTube video 'Leetcode 239: Sliding Window Maximum | Python Solution in Telugu | srkcodes'
Srk Codes 8 mins
Leetcode 239: Sliding Window Maximum | Python Solution in Telugu | srkcodes
YouTube video 'Sliding Window Maximum | LeetCode 239 | Python Solution'
ExDevPro 19 mins
Sliding Window Maximum | LeetCode 239 | Python Solution
YouTube video '239. Sliding Window Maximum || NEETCODE 150'
TechWithSaumya 17 mins
239. Sliding Window Maximum || NEETCODE 150
YouTube video '239. Sliding Window Maximum | Daily Leetcode Challenge | August | C++ | Java'
Mayur Programming Club 28 mins
239. Sliding Window Maximum | Daily Leetcode Challenge | August | C++ | Java
YouTube video 'LeetCode | 239. Sliding Window Maximum | Monotonic Queue'
Compl3x 13 mins
LeetCode | 239. Sliding Window Maximum | Monotonic Queue
YouTube video 'Sliding Window Maximum | Leetcode Hard | Asked by - Uber, Salesforce, Twilio, Bloomberg'
Code With Ease - By Varsha 22 mins
Sliding Window Maximum | Leetcode Hard | Asked by - Uber, Salesforce, Twilio, Bloomberg
YouTube video '239. Sliding Window Maximum | LeetCode in JavaScript'
JSer 34 mins
239. Sliding Window Maximum | LeetCode in JavaScript
YouTube video '239 || Sliding Window Maximum || C++ || Leetcode Daily Challenge'
CodeFreaks 14 mins
239 || Sliding Window Maximum || C++ || Leetcode Daily Challenge
YouTube video 'Sliding Window Maximum - LeetCode 239 - Python - Deque'
Alpha-Code 19 mins
Sliding Window Maximum - LeetCode 239 - Python - Deque
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

8 similar problems

Solved On The Same Day

10 easy 2 medium 15 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality