SDE & MLE Prep

912. Sort an Array

Problem

Sort the integer array nums in ascending order and return it, without built-in sort functions, in O(n log n) time and with as little extra space as you can.

Example: [5,1,1,2,0,0] → [0,0,1,1,2,5]

Constraints: n ≤ 5·10⁴.

Built-in sort is off limits, so implement an O(n log n) sort. Merge sort: sort each half recursively, then merge the two sorted halves with two pointers (stable, guaranteed O(n log n), O(n) extra space). Quicksort is in-place but needs a random pivot to avoid O(n²) on sorted/duplicate-heavy input; heap sort is in-place and O(n log n) but not stable.

Complexity: O(n log n) time, O(n) space.

class Solution:
    def sortArray(self, nums: List[int]) -> List[int]:
        if len(nums) <= 1:
            return nums
        mid = len(nums) // 2
        left, right = self.sortArray(nums[:mid]), self.sortArray(nums[mid:])
        out, i, j = [], 0, 0
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                out.append(left[i])
                i += 1
            else:
                out.append(right[j])
                j += 1
        return out + left[i:] + right[j:]