Sort an Array

35 min · sortArray()

Fifty thousand delivery times can land in no useful order. Before a dashboard can show the fastest runs, you need a sorter whose slow day is still fast.

Your function receives an integer array nums. Return an array containing exactly those values from smallest to largest. Ascending order here means non-decreasing order: every value is at least the value before it.

A few ground rules:

  • Write the sorting logic yourself. A call to your language's built-in sorting routine misses the point of this problem, even though the judge can only inspect your output.
  • Preserve every occurrence. If 7 appears four times in the input, it must appear four times in the result.
  • Give your algorithm a worst-case O(n log n) guarantee — a running-time bound that still holds when the input shape is as unfriendly as possible.

Constraints

  • 1 <= nums.length <= 50_000
  • -50_000 <= nums[i] <= 50_000
  • Duplicate values are allowed.

Hints

Grow sorted groups

One value is already sorted by itself. Merge neighboring one-value groups into sorted groups of length 2, then 4, then 8. How many rounds does that take?

Build a tournament

Another route keeps the largest remaining value at the front, moves it to the end, then repairs that structure. A max-heap keeps every parent at least as large as its children, so its largest value stays at the front.

Test the algorithm's bad day

Try 50,000 values that are already sorted, reverse-sorted, or all equal. If one of those shapes causes quadratic time — work that grows with n² — the guarantee isn't there yet.

Follow-up

Can you implement both merge sort with O(n) extra space and heap sort with O(1) extra space, then explain why neither one collapses to O(n²) on an already sorted array?

Visible cases

Examples

Example 1

ready
Input
nums = [
  5,
  2,
  3,
  1
]
Expected
[
  1,
  2,
  3,
  5
]
Why
1 comes first; 5 moves to the end

Example 2

ready
Input
nums = [
  5,
  1,
  1,
  2,
  0,
  0
]
Expected
[
  0,
  0,
  1,
  1,
  2,
  5
]
Why
duplicate 0s and 1s are preserved

Example 3

ready
Input
nums = [
  1
]
Expected
[
  1
]
Why
one value is already sorted

Interview signal

Asked at

AmazonGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite