Skip to content
RED SAGSkills

Sorted Squares of Readings

A sensor produces signed readings that are already sorted in non-decreasing order. Return the squares of the readings, also sorted in non-decreasing order.

Try to do it in linear time without calling a sort.

Example 1

Input: nums = [-4, -1, 0, 3, 10]
Output: [0, 1, 9, 16, 100]

Example 2

Input: nums = [-7, -3, 2, 3, 11]
Output: [4, 9, 9, 49, 121]

Constraints

  • 0 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order.
Hint 1

The largest square is always at one of the two ends.

Hint 2

Fill the output from the back using one pointer at each end.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Automation Test Engineer, Embedded Systems Engineer

Run checks your code on 2 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.