Sort an Array (LeetCode 912): Solution and Explanation

Medium
Array
Divide And Conquer
Sorting
Merge Sort
Heap Priority Queue

Sort an integer array in ascending order without a built-in sort. The array can hold 50,000 values, so the solution has to run in O(n log n).

Intuition

Bubble, insertion and selection sort are easy to write but do O(n²) work. At 50,000 elements that is over a billion steps, so they time out here.

Merging is the key cheap operation: two arrays that are already sorted can be combined into one sorted array in linear time. Keep a pointer at the front of each, repeatedly take the smaller front, and move that pointer forward.

So where do sorted arrays come from? Any single element is trivially sorted. Merge neighbouring singles and you have sorted runs of 2. Merge neighbouring 2s and you get runs of 4. After about log2(n) rounds of doubling, one run covers the whole array.

Each round touches every element once, and there are log2(n) rounds, which gives O(n log n). Doing it bottom-up with a loop over width avoids recursion entirely and needs just one scratch buffer.

Approach: Bottom-up merge sort

  1. Allocate a buffer buf with the same length as nums, and start with width = 1.
  2. While width < n, walk lo across the array in steps of 2 * width. The left run is [lo, mid) with mid = lo + width, and the right run is [mid, hi) with hi = min(lo + 2 * width, n).
  3. Merge with pointers i (left) and j (right): write the smaller of nums[i] and nums[j] into buf[k], taking the left one on ties so equal values keep their order.
  4. When one run is exhausted, copy the rest of the other run into the buffer. It is already sorted.
  5. Copy buf[lo:hi] back into nums[lo:hi], then move to the next pair.
  6. After the pass, double width. When width >= n, the array is one sorted run; return it.

Step-by-step example

nums = [5,2,3,1]
  1. width = 1: runs are [5], [2], [3], [1].
  2. Merge [5] and [2]: 2 < 5, write 2, then copy the leftover 5. Positions 0 to 1 become [2,5].
  3. Merge [3] and [1]: 1 < 3, write 1, then copy 3. Positions 2 to 3 become [1,3]. The array is [2,5,1,3].
  4. width = 2: merge [2,5] with [1,3]. Take 1, then 2, then 3, then copy the leftover 5.
  5. The array is [1,2,3,5]. width becomes 4, which is not less than n, so return.

Code: Python, Java, C++

1class Solution:
2    def sortArray(self, nums: List[int]) -> List[int]:
3        n = len(nums)
4        buf = [0] * n
5        width = 1
6        while width < n:
7            for lo in range(0, n - width, 2 * width):
8                mid, hi = lo + width, min(lo + 2 * width, n)
9                i, j, k = lo, mid, lo
10                while i < mid and j < hi:
11                    if nums[i] <= nums[j]:
12                        buf[k] = nums[i]
13                        i += 1
14                    else:
15                        buf[k] = nums[j]
16                        j += 1
17                    k += 1
18                buf[k:hi] = nums[i:mid] + nums[j:hi]
19                nums[lo:hi] = buf[lo:hi]
20            width *= 2
21        return nums
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Counting sort O(n + k)
Bottom-up merge sort O(n log n)
Top-down merge sort O(n log n)
Heap sort O(n log n)
Time

O(n log n)

Each pass over the array merges every element exactly once, which is O(n), and the run width doubles each pass, so there are about log2(n) passes.

Space

O(n)

One buffer of length n holds merge output. The bottom-up version needs no recursion stack.

Other approaches

Top-down merge sort (time O(n log n), space O(n))

Split the array in half recursively, sort both halves, then merge. Same work and same buffer, plus O(log n) recursion depth.

Heap sort (time O(n log n), space O(1))

Build a max-heap in place, then repeatedly swap the root to the end and sift down. It uses O(1) extra space but is not stable and has poorer cache behaviour.

Counting sort (time O(n + k), space O(k))

Values lie in [-50000, 50000], so you can count occurrences in an array of 100,001 slots and rebuild the output. Linear time, but only because the value range is small.

Common mistakes

  • Using quicksort with a fixed pivot. LeetCode includes already sorted and all-equal inputs that push it to O(n²) and time it out.
  • Forgetting the leftovers after the two-pointer loop. One run always finishes first, and its partner's tail must still be copied.
  • Computing hi as lo + 2 * width without capping at n. The last pair is often shorter than a full block.
  • Using < instead of <= when comparing fronts. The answer is still sorted, but the sort loses stability.

Frequently asked questions

Why does the loop condition use lo + width < n?

A pair only needs merging when a right run exists. If lo + width >= n, the remaining block is a lone left run that is already sorted, so it can stay where it is.

Is merge sort stable?

Yes, as long as ties take the element from the left run. Equal values then keep their original relative order.

Why not just call the language's sort?

The problem forbids it. The point is to implement an O(n log n) algorithm yourself, and the built-in would also hide the merge step this problem is about.

Can merge sort be done without the O(n) buffer?

In-place merge variants exist but are complicated and slower in practice. If O(1) extra space matters, heap sort is the usual choice.