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;
}
};
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 76: Minimum Window Substring
- problem 155: Min Stack
- problem 159: Longest Substring with At Most Two Distinct Characters
- problem 265: Paint House II
- problem 1696: Jump Game VI
- problem 2398: Maximum Number of Robots Within Budget
- problem 2517: Maximum Tastiness of Candy Basket
- problem 2530: Maximal Score After Applying K Operations
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- 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