AAlgoLoopSpaced repetition for LeetCode
EASYTwo PointersLeetCode ↗

Squares of a Sorted Array

The key idea

The input is already sorted, so the largest square always sits at one of the two ends (the most negative or the most positive value). Walk two pointers inward from both ends, take the bigger square each step, and fill the answer from the back. This skips the re-sort entirely.

Problem

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

The twist is that nums may contain negative numbers, so a negative value with a large magnitude squares to a large positive number. Because the array is already sorted, the biggest squares live at the two ends — can you build the answer in O(n) time without sorting again?

Constraints

Examples

Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100]
Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Two Pointers problems