Sort squares of a sorted array in one pass

To sort squares of a sorted array, you don’t want to use any sorting algorithms such as bubble sort. Because it takes O(nlogn) ~ O(n^2) time. Here we introduce a better way to sort in one pass.

sort square

The solution is using two pointers. Initialize two pointers, one points to the first element, and the other points to the last element. Then compare the absolute value of these two elements pointed by the indices. Put the square of the larger one at the end of the output array. Then increase or decrease the larger one’s index. When all the elements have been compared, the output is the sorted square. With the optimized version of sort squares of a sorted array, the solution has the time complexity to O(n).

VMwave Interview Question:
Input: sorted integers: example: [-2, 1, 2, 3]
Output: sorted squares of the input: [1, 4, 4 ,9]




Input array: [-2, 1, 2, 3]
Sorted squares: [1, 4, 4, 9]

O Notation:
Time complexity: O(n)
Space complexity: O(n)

What does “squares of a sorted array” mean in leetcode?

Given a sorted array, return the squares of each element in the array. Meanwhile, the return array must be sorted as well. Do not use sorting algorithm.
sort square

Download SortSquares.js
Sort squares with optimization (YouTube)

Comments are closed