Problem 912

Abstract / Summary

Given an array of integers, arrange the numbers in non-decreasing order.

Note

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

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;
    }
};
20 lines | 542 bytes | submitted September 28, 2023 | GitHub   18% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

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
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 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.

written by openai gpt

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.

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 = 4.5 | μ = 4.92 | σ = 1.84

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++ 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
36 links | 21 authors | 11 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

32 solutions   September 28, 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