Ctrl K

Squares in Order

Easy
A sensor reports deviations from the norm as integers readings, already sorted in non-decreasing order; some of them may be negative. The report needs their squares. Return the squares of all numbers in readings, sorted in non-decreasing order. Squaring everything and sorting is easy. Try to do it in O(n) without sorting.
Example 1
readings=[-6, -2, 1, 5] → [1, 4, 25, 36]

The squares are 36, 4, 1, 25; in ascending order that is 1, 4, 25, 36.

Example 2
readings=[-3, -3, 0, 3] → [0, 9, 9, 9]

Equal squares all stay in the answer: three 9s.

Example 3
readings=[2, 8] → [4, 64]
Constraints
  • 1 ≤ len(readings) ≤ 10⁴
  • -10⁴ ≤ readings[i] ≤ 10⁴
  • readings is sorted in non-decreasing order
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMerge Into the Spare Tail EasyValues in Both Lists EasyShared Values With Repeats EasyCake Slices for Guests EasyEvens to the Left Easy
loading Python…
Input
readings=[-6, -2, 1, 5]
Expected
[1, 4, 25, 36]

Run checks the first 3 tests in your browser. Submit checks all 117 tests on the server, hidden ones included.