easyTwo pointers target 15 min
Squares of a sorted list
You get a list of integers nums, sorted from smallest to largest. It may hold negative numbers. Return a new list holding the square of every number, also sorted from smallest to largest, and leave nums unchanged.
Negatives are the catch: -4 is smaller than 3, but its square, 16, is bigger than 9.
Example 1
Input
nums = [-3, -1, 0, 2, 4]Output[0, 1, 4, 9, 16]The squares in list order are 9, 1, 0, 4, 16. Sorted, they are 0, 1, 4, 9, 16.
Example 2
Input
nums = [-5, -4, 1]Output[1, 16, 25]The squares in list order are 25, 16, 1.
Example 3
Input
nums = [-6, -2, -1]Output[1, 4, 36]All negative: the squares come out in reverse order.
Constraints
0 ≤ len(nums) ≤ 104
-104 ≤ nums[i] ≤ 104
numsis sorted from smallest to largest.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.