Squares of a Sorted Array
Real-world version: Sorted Drift EnergiesThe statement here is our own: the same inputs, outputs and technique.
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.
def drift_energies(drift: list[int]) -> list[int]:public int[] driftEnergies(int[] drift)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's