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(n log n) time complexity and with the smallest space complexity possible.

Input & Output

Example 1 — Basic Sorting
$ Input: nums = [5,2,8,6,1,9,4]
Output: [1,2,4,5,6,8,9]
💡 Note: Sort the array in ascending order: all elements arranged from smallest to largest
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4,5]
Output: [1,2,3,4,5]
💡 Note: Array is already sorted, return as is
Example 3 — Reverse Order
$ Input: nums = [5,4,3,2,1]
Output: [1,2,3,4,5]
💡 Note: Array in reverse order, needs complete reordering to ascending

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • -5 × 104 ≤ nums[i] ≤ 5 × 104

Visualization

Tap to expand
Sort an Array: Unsorted → SortedInput: [5,2,8,6,1,9,4]5286101234SORTOutput: [1,2,4,5,6,8,9] (sorted ascending)1245689Elements rearranged in ascending order: smallest → largest
Understanding the Visualization
1
Input
Unsorted array of integers
2
Process
Apply sorting algorithm (merge sort, heap sort, etc.)
3
Output
Array sorted in ascending order
Key Takeaway
🎯 Key Insight: Use divide-and-conquer algorithms like merge sort to achieve optimal O(n log n) time complexity
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 6
85.0K Views
High Frequency
~15 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen