All problems
0069EasyArrayTwo PointersSorting

Sorted Drift Energies

Tracked in this browser only
Write code

Trains the technique from

LeetCode 977Squares of a Sorted Array

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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