Squared Deviations

Easytwo pointersAlso known as Squares of a Sorted Array

A greenhouse sensor logs how far each reading is from the ideal temperature: negative for too cold, positive for too warm. The log is sorted from lowest to highest, for example [-7, -3, 0, 2, 5].

The climate system punishes big misses more, so its cost is the square of each deviation. It wants those costs sorted from smallest to largest.

Your task

Write squaredSorted(deviations). Return a new list with the square of every number, sorted from smallest to largest.

Aim for a single pass over the list, and use the fact that the input is already sorted.

squaredSorted(deviations: int[]) → int[]

Examples

Example 1
Input
deviations = [-7, -3, 0, 2, 5]
Output
[0, 4, 9, 25, 49]
Why

The squares in input order are 49, 9, 0, 4, 25. Sorted, they are 0, 4, 9, 25, 49. The biggest squares come from the two ends of the input, -7 and 5.

Example 2
Input
deviations = [-4, -1, 0, 3, 10]
Output
[0, 1, 9, 16, 100]
Why

The squares in input order are 16, 1, 0, 9, 100. The largest, 100, comes from the right end, and the next largest, 16, comes from the left end.

Constraints

  • 0 ≤ deviations.length ≤ 10,000
  • -10,000 ≤ deviations[i] ≤ 10,000
  • deviations is sorted in non-decreasing order.
Start with brute force

Square every number and then sort the result. This is correct and takes only a few lines.

The sort costs O(n log n) and ignores that the input was already sorted, which tells you where the big values are.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code