Two Pointers · Both ends

Squares of a Sorted Array Visualizer

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

Square, then sortSquaring and sorting is correct, and it does more work than the order of the input requires.
Write from the backCompare the absolute values at the two ends. Place the larger square at the next free slot from the right, then move that end inward.

Interactive solution

Both ends of the input, and the output filling from the right
L, R = 0, n - 1
write from the last index backward
if abs(a[L]) >= abs(a[R]): place a[L] squared; L += 1
else: place a[R] squared; R -= 1
return the squares
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(n)Each end moves inward once.
MemoryO(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