C++ 0075.cpp
class Solution {
public:
void sortColors(vector<int>& nums) {
vector<int> freq(3, 0);
for (auto n : nums)
freq[n]++;
nums.clear();
nums.insert(nums.end(), freq[0], 0);
nums.insert(nums.end(), freq[1], 1);
nums.insert(nums.end(), freq[2], 2);
}
};
Difficulty
and has an acceptance rate of about 70% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Sorting
- Two Pointers
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 provided implementation solves the classic “sort colors” problem, where an input array contains only the integers 0, 1, and 2, representing three distinct colors. The algorithm rearranges the elements so that all 0s appear first, followed by 1s, and finally 2s. It achieves this by counting the occurrences of each value and then reconstructing the array based on those counts. The approach is deterministic, runs in linear time with respect to the length of the input, and uses only a small, fixed amount of auxiliary storage.
Frequency Counting
The first logical block creates a three-element frequency vector initialized to zero. It then iterates over the original nums vector, incrementing the appropriate counter for each element.
vector<int> freq(3, 0);
for (auto n : nums)
freq[n]++;
Because the input domain is limited to the indices 0, 1, 2, the freq vector directly maps each possible value to its count. This eliminates the need for conditional branches or hash-based structures, keeping the operation tight and cache-friendly.
Clearing the Original Container
After the frequencies have been recorded, the original nums vector is cleared. This step discards the previous ordering and prepares the container for a fresh insertion sequence.
nums.clear();
Calling clear() retains the allocated capacity of the vector, which means that subsequent insertions can reuse the existing memory block without triggering additional allocations. This subtle reuse contributes to the overall efficiency, especially for large inputs.
Rebuilding the Sorted Sequence
The final phase repopulates nums by inserting the appropriate number of each color in order. The insert method is invoked three times, each time specifying the count of elements to add and the value to insert.
nums.insert(nums.end(), freq[0], 0);
nums.insert(nums.end(), freq[1], 1);
nums.insert(nums.end(), freq[2], 2);
Using the overload of insert that takes a count and a value allows the implementation to add a contiguous block of identical elements in a single call. Internally, this translates to a bulk memory operation rather than a per-element push, reducing loop overhead and improving data locality.
Edge Cases Handled
The algorithm gracefully handles an empty input vector. In that scenario, the frequency counters remain zero, the clear() call leaves the vector empty, and the three insert calls each attempt to add zero elements, resulting in no change to the container.
When the input consists exclusively of a single color-such as all 0s, all 1s, or all 2s-the frequency vector records a non-zero count for only one index. The reconstruction phase then inserts a block of that single value while the other two insert calls add nothing, yielding a correctly sorted array without extra work.
If the input already appears in sorted order, the algorithm still performs the counting and rebuilding steps, but the final arrangement matches the original ordering. The method does not rely on any assumptions about the initial distribution, ensuring correctness regardless of pre-existing order.
Performance Optimizations
The design leverages a counting sort paradigm, which is optimal for a fixed, small range of integer keys. By avoiding comparison-based sorting, the implementation eliminates the overhead associated with element swaps and recursive partitioning.
Memory reuse is achieved through the combination of clear() and the subsequent insert calls. Because clear() does not deallocate the underlying storage, the vector’s capacity remains sufficient for the final size, preventing repeated allocations and deallocations that could degrade performance.
Bulk insertion via vector::insert with a count argument reduces the number of function calls and loop iterations required to rebuild the array. This approach allows the standard library to perform a single contiguous memory copy for each color block, which is typically faster than inserting elements one by one.
Overall, the code exhibits a tight control flow with minimal branching, leverages contiguous memory operations, and confines auxiliary storage to a constant-size array, all of which contribute to an efficient execution profile for the problem at hand.
ELI5 - Simplified Explanation
Imagine a big box filled with lots of mixed up crayons that are only red, white, and blue. To tidy them up, the first thing is to count how many of each color are in the box. A small list is made to keep track of the count for red, the count for white, and the count for blue.
Once every single crayon is counted, the box is emptied out so it is perfectly clean. Then, all the red crayons are put back first, followed by all the white crayons, and finally all the blue crayons go in last. Now, all the matching colors are sitting together in a neat row, just like magic.
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 | Java | C# | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 280: Wiggle Sort
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
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