Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
nums = [-4,-1,0,3,10][0,1,9,16,100]In a sorted array, the largest absolute value is always at one of the two ends — either the leftmost (most negative) or rightmost (most positive). By comparing ends and filling the result array from back to front, we always place the correct largest square without sorting. The two pointers meet in the middle.
Squaring everything and then sorting costs O(n log n). Negative numbers break the order: minus 4 squared is bigger than 3 squared.
The biggest square always comes from one of the two ends, because those have the largest absolute values. So use two pointers at both ends, and fill the answer from the back. Each time, place the bigger square, and move that pointer inward.
In a sorted array with negatives, the largest squares sit at the two ends. Fill the result from the back with two pointers.
Run the animation above on your own input, or watch the 1:31 video explanation of Squares of a Sorted Array with a dry run and Java code.