Squares in order
Inputs
values is a list of 0 to 12 whole numbers in increasing order, each from -9 to 9.
Your tasks
- Set
leftto 0 andrightto the last position, and createsquares, a list with one 0 for each number invalues. - Fill
squaresfrom the back. Compare the squares ofvalues[left]andvalues[right]. Put the bigger one in the next spot from the back and move that marker inward. - Complete
sortedSquaresso it returnssquares. Return it, do not print it.
Example
With values = [-4, -1, 0, 3, 10], sortedSquares returns [0, 1, 9, 16, 100].
Rules
- The result is in increasing order.
Test data
TEST DATA 1: values is [-4, -1, 0, 3, 10]
TEST DATA 2: values is []
Practice focus
Two pointers and sliding windows: loops that move two positions instead of one. Two pointers and sliding windows turn many quadratic answers into linear ones.