Sort an Array

Given an array of integers `nums`, sort it in ascending order and return it. Do not use any built-in sort: the solution must run in O(n log n) time with as little extra space as possible.

30:00

Sort an Array
medium
Free written solution
Topics
Companies

Given an array of integers nums, sort it in ascending order and return it. Do not use any built-in sort: the solution must run in O(n log n) time with as little extra space as possible.

Example 1:
Input: {"nums":[5,2,3,1]}
Output: [1,2,3,5]
Constraints:
  • 1≤nums.length≤5×1041 \leq \text{nums.length} \leq 5 \times 10^4

  • −5×104≤nums[i]≤5×104-5 \times 10^4 \leq \text{nums}[i] \leq 5 \times 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[5,2,3,1]}

sorted runs of 1

5231

left run

right run

merged

shaded blocks = sorted runs

4 numbers. Every single element is already a sorted run of length 1; merge sort grows runs by doubling.

Variables
VariableValue
n4
DepthFunction Call
Stack empty
0/20