Squares of a Sorted Array

Given a sorted array of integers, return a new array containing the squares of each number in non-decreasing order. The sorted input allows a two-pointer merge-like approach from both ends.

Input Format

nums = sorted array of integers

Output Format

sorted array of squares

Constraints

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

Examples

Example 1:

Input:

nums = [-4,-1,0,3,10]

Output:

[0,1,9,16,100]

Explanation:

Squaring breaks the original order, so the output must be rebuilt in sorted order.

Example 2:

Input:

nums = [-7,-3,2,3,11]

Output:

[4,9,9,49,121]

Explanation:

The squares are sorted after using the largest absolute value from either end.

Loading...
Squares of a Sorted Array