Squares of a Sorted Array

Two Pointers, problem 3 of 7

Squares of a Sorted Array

Easy

LC #977

sortingopposite ends

Not attempted yet

nums is sorted in non-decreasing order and may contain negative numbers. Return a new list with the square of each number, also sorted in non-decreasing order.

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]

Example 3

Input: nums = [-5, -3, -1]
Output: [1, 9, 25]

Constraints

  • 1 ≤ len(nums) ≤ 2 · 10⁵
  • -10⁵ ≤ nums[i] ≤ 10⁵
  • Follow-up: O(n) without sorting the squares

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.