#977

Squares of a Sorted Array

Easy Opposite ends, fill from back

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Given a sorted array that may contain negatives, return the squares of all elements in sorted order.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: square everything and return it sorted. Negatives make the squares unsorted.

Why this works: the biggest square is always at one of the two ends. Fill the answer from the back with the bigger end.

Example: [-4, -1, 0, 3, 10]

16 vs 100 → 100 at the back16 vs 9 → 161 vs 9 → 91 vs 0 → 1, then 0[0, 1, 9, 16, 100]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Squaring then sorting — O(n log n) and misses the two-pointer idea.