C++ 0912.cpp
class Solution {
public:
vector<int> sortArray(vector<int>& nums)
{
if (nums.size() <= 1)
return nums;
// Python's just too slow ... had to switch to C++
// in-place Radix-Sort
map<int, int> radix; // slightly cheating: maps are sorted by default
for (auto n : nums)
radix[n]++;
size_t pos = 0;
for (auto r : radix)
for (int i = 0; i < r.second; i++)
nums[pos++] = r.first;
return nums;
}
};
Difficulty
and has an acceptance rate of about 56% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Bucket Sort
- Counting Sort
- Divide And Conquer
- Heap (Priority Queue)
- Merge Sort
- Radix Sort
- Sorting
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 Solution class implements a sorting routine for a vector of integers. The method sortArray receives a reference to a vector, checks for trivial cases, and then builds a frequency map to reorder the elements in non-decreasing order. The algorithm leverages the ordered nature of std::map to produce a sorted sequence without an explicit comparison-based sort.
Key Steps
The first logical step is a size check that short-circuits the function when the input contains zero or one element. This guard eliminates unnecessary work for already trivial inputs.
if (nums.size() <= 1)
return nums;
Next, the code constructs a std::map<int,int> named radix. The map stores each distinct integer from the input as a key and its occurrence count as the associated value. Because std::map maintains its keys in sorted order, the map inherently arranges the distinct values from smallest to largest.
map<int, int> radix; // slightly cheating: maps are sorted by default
for (auto n : nums)
radix[n]++;
After the frequency map is populated, the algorithm iterates over the map in ascending key order. For each key-value pair, it writes the key back into the original vector the number of times indicated by the count. An index variable pos tracks the current write position within the vector.
size_t pos = 0;
for (auto r : radix)
for (int i = 0; i < r.second; i++)
nums[pos++] = r.first;
Finally, the method returns the now-sorted vector.
return nums;
Edge Cases Handled
The initial size check gracefully handles empty vectors and single-element vectors, returning them unchanged. This avoids unnecessary map construction and iteration for inputs that are already sorted by definition.
When the input contains duplicate values, the frequency map aggregates the count, and the nested loop reproduces each duplicate the correct number of times. This ensures that the output preserves the multiplicity of each element while still ordering them.
If the input includes negative integers, the map’s ordering still correctly positions them before positive values because std::map uses the natural ordering of int. Thus the algorithm works uniformly across the full range of signed integers.
Performance Optimizations
The algorithm benefits from the fact that std::map maintains sorted keys internally, eliminating the need for a separate sorting pass. By counting occurrences first, the code reduces the number of write operations to the original vector: each distinct value is written exactly as many times as it appears, avoiding repeated comparisons.
The use of a single pass to fill the map (O(n) insertions) followed by a linear reconstruction of the vector (O(n) writes) yields a predictable execution pattern. The map’s balanced tree structure provides logarithmic insertion time, but the overall approach avoids the overhead of more complex comparison-based sorts for data sets with many repeated values.
The in-place reconstruction writes directly into the original vector, avoiding allocation of an auxiliary container for the sorted result. This reduces memory pressure and improves cache locality during the final write phase.
ELI5 - Simplified Explanation
Imagine you have a big pile of mixed-up building blocks with different numbers painted on them. Your goal is to line them up so the smallest numbers are on the left and the biggest numbers are on the right.
The code starts by looking at your pile of blocks. If you only have one block or no blocks at all, they are already perfectly lined up, so it leaves them exactly as they are.
If you have more blocks, the computer uses a special box shelf that keeps things organized automatically. It picks up each block one by one and places it into the shelf in the right spot based on its number. Because this shelf is very smart, it always keeps the numbers in order from smallest to biggest as it gathers them.
After every block is tucked into the shelf, the computer walks along the shelf from start to finish. It takes the blocks back out in order and puts them back into your original line. Now, all your blocks are sitting in a tidy row, and you are ready to play.
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++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | JS | Go | Rust | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 880: Decoded String at Index
- problem 923: 3Sum With Multiplicity
- problem 973: K Closest Points to Origin
- problem 1010: Pairs of Songs With Total Durations Divisible by 60
- problem 1054: Distant Barcodes
- problem 1079: Letter Tile Possibilities
- problem 1090: Largest Values From Labels
- problem 1347: Minimum Number of Steps to Make Two Strings Anagram
- problem 1366: Rank Teams by Votes
- problem 1419: Minimum Number of Frogs Croaking
- problem 1738: Find Kth Largest XOR Coordinate Value
- problem 1814: Count Nice Pairs in an Array
- problem 1985: Find the Kth Largest Integer in the Array
- problem 2018: Check if Word Can Be Placed In Crossword
- problem 2150: Find All Lonely Numbers in the Array
- problem 2182: Construct String With Repeat Limit
- problem 2225: Find Players With Zero or One Losses
- problem 2232: Minimize Result by Adding Parentheses to Expression
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2284: Sender With Largest Word Count
- problem 2343: Query Kth Smallest Trimmed Number
- problem 2526: Find Consecutive Integers from a Data Stream
- problem 2844: Minimum Operations to Make a Special Number
- problem 2860: Happy Students
- problem 906: Super Palindromes
- problem 992: Subarrays with K Different Integers
- problem 1106: Parsing A Boolean Expression
- problem 1601: Maximum Number of Achievable Transfer Requests
- problem 2081: Sum of k-Mirror Numbers
- problem 2122: Recover the Original Array
- problem 2416: Sum of Prefix Scores of Strings
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