What is Squares of a Sorted Array
The array is sorted and may contain negatives. Return the squares of every value, sorted from small to large. The largest square is at one of the two ends, because a very negative value squares to a large number.
-4 -1 0 3 10 0 1 9 16 100
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each end moves inward once. |
| Memory | O(n) | The squares are written into a new array. |
Implementation
def sorted_squares(a):
n = len(a)
out = [0] * n
l, r, p = 0, n - 1, n - 1
while l <= r:
if abs(a[l]) >= abs(a[r]):
out[p] = a[l] * a[l]
l += 1
else:
out[p] = a[r] * a[r]
r -= 1
p -= 1
return out