Easy · Opposing Magnitudes
Understand → Visualise → Practice.
Square every ascending input value and return the squares in ascending order in linear time.
In a sorted array the largest absolute value is at the left or right end. Fill the result from the back by comparing the two ends.
left = 0, right = n − 1.
Compare |nums[left]| and |nums[right]|, write the larger square at the current back position, and move that pointer.
Repeat until every position is filled.
O(n) time and O(n) space for the output.
Squaring and then sorting is O(n log n).
Read the full guide first: Two Pointers and Sliding Windows.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.