Show problems as
Classic problem #977EasyArrayTwo PointersSorting

Squares of a Sorted Array

Real-world version: Sorted Drift Energies
Tracked in this browser only
Read Squares of a Sorted Array on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstTwo Pointers · Arrays, animated step by step

A calibration rig logs how far each sensor sits from its target. The log is drift, where a negative entry means the sensor reads low, a positive entry means it reads high, and the entries are already arranged from lowest to highest, so ties may sit next to each other.

The rig grades a sensor by its drift energy, the entry multiplied by itself, which wipes out the sign. Produce the drift energy of every entry, arranged from smallest to largest.

Sorting the energies afterwards works but throws away what the log already tells you. Aim for one pass over drift.

Examples

Example 1

Input
drift = [-9, -4, 0, 2, 7]
Output
[0, 4, 16, 49, 81]

The energies are 81, 16, 0, 4 and 49; arranged from smallest to largest they read 0, 4, 16, 49, 81. The largest energy came from the leftmost entry.

Example 2

Input
drift = [-8, -5, -3, -1]
Output
[1, 9, 25, 64]

Every sensor reads low, so squaring flips the arrangement end for end.

Example 3

Input
drift = [-2, -2, 0, 2, 2]
Output
[0, 4, 4, 4, 4]

Four entries share the energy 4, and each of them is reported.

Constraints

  • 1 <= drift.length <= 10^4
  • -10^4 <= drift[i] <= 10^4
  • drift is arranged from lowest to highest value

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def drift_energies(drift: list[int]) -> list[int]:
Java
public int[] driftEnergies(int[] drift)