Sort squares with optimization – Code

Sort squares is to sort the square of elements in a sorted array. Sounds easy, right? Since it uses sorting algorithms, the time complexity is O(n^2). Now you are asked to optimize it. The complexity should be O(n).

How to optimize? We can use the “merge two sorted arrays” approach. We divide the sorted array into half. The first half has all the negative numbers. The second half has all the numbers that are equal or larger than zero. Then we merge the two arrays of the squares of the original numbers. This solution has the time complexity to O(n).

You can see that sort squares is a “merge two sorted arrays” question under disguise.

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


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

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

If you have any questions or want to put comments, please post at youtube. I will answer you!
The code displayed here is the simplified version after the enhancement in the 2nd edition of Java coding interview pocket book.

Sort squares with optimization tutorial
Merge two sorted arrays (2 solutions)

Comments are closed