Skip to the code
cf.
+10 XP

#100 Sorted Squares of Scroll Offsets

easy

A scroll-snap feature records how far each snap point is from the current position, as signed offsets in offsets, sorted ascending. Negative offsets are above the viewport and positive ones below.

To rank snap points by distance, it needs the squares of the offsets in ascending order. Write sortedSquares(offsets) that returns a new array of every offsets[i] * offsets[i], sorted ascending, in O(n) time.

Example 1

Input: offsets = [-6,-2,0,3,5]
Output: [0,4,9,25,36]

The squares are 36, 4, 0, 9, 25; sorted, they are 0, 4, 9, 25, 36.

Example 2

Input: offsets = [-9,-4,-1]
Output: [1,16,81]

All negative: the biggest square comes from the first offset.

Constraints

  • 0 <= offsets.length <= 100000
  • -10^4 <= offsets[i] <= 10^4
  • offsets is sorted ascending.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).