Sort an Array — LeetCode 912 Python Solution

MediumArrayDivide and ConquerBucket SortCounting SortRadix SortSortingHeap (Priority Queue)Merge Sort
Problem
#912
Reading time
4 min

The problem

Given an array of integers nums, sort the array in ascending order and return it. You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.

Example

Input
nums = [5,2,3,1]
Output
[1,2,3,5]
Explanation
After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).

Python solution

Python
class Solution:
    def sortArray(self, nums: List[int]) -> List[int]:
        def quick_sort(l, r):
            if l >= r:
                return
            x = nums[randint(l, r)]
            i, j, k = l - 1, r + 1, l
            while k < j:
                if nums[k] < x:
                    nums[i + 1], nums[k] = nums[k], nums[i + 1]
                    i, k = i + 1, k + 1
                elif nums[k] > x:
                    j -= 1
                    nums[j], nums[k] = nums[k], nums[j]
                else:
                    k = k + 1
            quick_sort(l, i)
            quick_sort(j, r)

        quick_sort(0, len(nums) - 1)
        return nums

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 912. Sort an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 912. Sort an Array?
LeetCode 912. Sort an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 912. Sort an Array?
The Python solution on this page runs in O(n log n).
What is the space complexity of LeetCode 912. Sort an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 912. Sort an Array cover?
LeetCode 912. Sort an Array is tagged Array, Divide and Conquer, Bucket Sort, Counting Sort, Radix Sort, Sorting, Heap (Priority Queue) and Merge Sort on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview