Skip to main content
Back to ChallengesSort an ArrayEasy 15 min

Sort an Array

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.

Examples

Input: nums = [5,2,3,1]
Output: [1,2,3,5]
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).

Constraints

  • 1 <= nums.length <= 5 * 10^4
  • -5 * 10^4 <= nums[i] <= 5 * 10^4

Complexity Analysis

Time
O(N log N)
standard merge sort complexity.
Space
O(N)
auxiliary arrays created during merge.

Test Cases

#1 Small array
Input: nums = [5,2,3,1]
Expected: [1,2,3,5]
#2 Array with duplicates
Input: nums = [5,1,1,2,0,0]
Expected: [0,0,1,1,2,5]
JavaScript
Output
Click "Run Code" to see output here...