Back to ArraysSquares of a Sorted Array
Easy

Squares of a Sorted Array

EasyRecommendedTwo Pointers

Given an array sorted in non-decreasing order (which may include negative numbers), return a new array of the squares of each number, also sorted in non-decreasing order.

Examples

Example 1

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

Explanation: Squaring removes sign information, so -4 (16) lands after 3 (9) even though -4 < 3.

Example 2

Input:
nums = [-7,-3,-1]
Output:
[1,9,49]

Explanation: All-negative input still produces an ascending list of squares, largest magnitude last.

Example 3

Input:
nums = [1,2,4]
Output:
[1,4,16]

Explanation: All non-negative input squares in the same order it started in.

Constraints

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

Loading editor…

Code execution is coming soon.