Sort an integer array in O(n log n) time without built-in sort functions
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Sort an integer array into ascending order without any built-in sort, in O(n log n) time and with as little extra space as possible. It tests whether you can implement a worst-case O(n log n) comparison sort by hand and reason about the time and space costs of different sorting algorithms.
Constraints
- 1 <= len(nums) <= 5 * 10^4
- -5 * 10^4 <= nums[i] <= 5 * 10^4
- Do not use a built-in sort or heap routine; aim for O(n log n) time and the smallest possible extra space.
Examples
Input: ([5, 2, 3, 1],)
Expected Output: [1, 2, 3, 5]
Explanation: Source example: four distinct values come back in ascending order.
Input: ([5, 1, 1, 2, 0, 0],)
Expected Output: [0, 0, 1, 1, 2, 5]
Explanation: Source example: both copies of 0 and both copies of 1 are kept.
Hints
- Swapping neighbors until nothing moves takes O(n^2) comparisons on 5 * 10^4 elements; look for a method that spends about O(log n) work per element.
- Every copy of a repeated value must reach the output, so never skip or merge equal values.
- To keep extra space small, think about which O(n log n) methods can rearrange the array in place.