Squared Deviations

Easytwo pointersAlso known as Squares of a Sorted Array

A greenhouse sensor records how far each reading is from the ideal temperature. Too cold gives a negative number, too warm a positive one. The log is already sorted from lowest to highest, for example [-7, -3, 0, 2, 5].

The climate system cares about the size of each miss, and it punishes big misses more, so it uses 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. The input is sorted; use that.

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: 0, 4, 9, 25, 49. Notice the biggest squares came 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

Squares in order: 16, 1, 0, 9, 100. The largest, 100, comes from the right end. 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, then sort the result. It is two lines of code and it is correct.

It costs O(n log n) because of the sort, and it ignores the fact that the input was already sorted. The sorted input is a gift: it 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