Sort the integer array nums from smallest to largest and return it.
Do it without calling the language's built-in sort, and in O(n log n) time or better, using as little extra memory as you can. Values may repeat and may be negative.
Example 1
Input: nums = [3, -1, 2, 3, 0] Output: [-1, 0, 2, 3, 3] Why: both 3s stay, placed side by side at the end
2 more examples and the constraints
Example 2
Input: nums = [8, 8, -4, 5, 0, -4] Output: [-4, -4, 0, 5, 8, 8] Why: negatives come first, repeats stay together
Example 3
Input: nums = [42] Output: [42] Why: one value is already sorted
Constraints
- nums holds between 1 and 50,000 values
- Every value lies between −50,000 and 50,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Insertion sortO(n²)
- Merge sortO(n log n)
- Counting sortO(n + k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 values | Verdict |
|---|---|---|---|
| Insertion sort | O(n²) | Too slow on falling input | |
| Merge sort | O(n log n) | Passes for any value range | |
| Counting sort | O(n + k) | Best here; range is small |
n = number of values, k = hi − lo + 1, at most 100,001.
Edge cases to test
- One value. [42] is returned as it is.
- Negative values. Counting sort must offset by lo; merge sort needs nothing special.
- Repeats. [6, 6, 6, 6]: every approach must keep all four copies.
- Falling order. The worst case for insertion sort: every value slides to the front.
- Both range limits. −50,000 and 50,000 together make the counter array its full 100,001 slots.
Common mistakes
- Using
<in the merge, which still sorts but loses stability. - Indexing the counter array with x directly, which breaks on negative values.
- Picking a quicksort pivot at a fixed position, which turns sorted or all-equal input into O(n²).
How to talk through it
- 1Clarify. Is the built-in sort off limits? What is the value range? Should it be stable or in place?
- 2Give the simple version. Insertion sort is short and in place, but O(n²) on falling input.
- 3Reach n log n. Merge sort splits in half, sorts both halves and merges them in linear time.
- 4Use the range. With only 100,001 possible values, counting sort tallies them and writes them back in O(n + k).
- 5Test out loud. Run one value, repeats, negatives and an array in falling order.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?