Squares of a Sorted Array
Easy
Topics
Given an array nums sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order.
Example 1
nums
squares
negative — squares in reverse order
Squaring breaks the sort order, because the largest square can come from either end. Comparing the two ends and filling the output from the back gives it in one linear pass, instead of squaring then re-sorting.
Top row is the input; below it the sorted squares.
Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100]
Example 2
nums
squares
negative — squares in reverse order
Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]
Constraints
- 1 <= nums.length <= 10^4
- -10^4 <= nums[i] <= 10^4
- nums is sorted non-decreasing.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The largest squares come from the extremes (most negative or most positive). So fill the output from the back using two pointers at both ends.
This beats the trivial "square then sort" O(n log n) with a clean O(n) merge.
Approach
- Pointers
l,rat both ends; write position at the end of the output. - Compare squares at
landr; place the larger at the current output slot and move that pointer inward. - Repeat until the pointers cross.
Walkthrough
nums = [-4,-1,0,3,10]
squares extremes: 16 vs 100 -> place 100
16 vs 9 -> 16 ... result [0,1,9,16,100]Complexity
- Time — O(n): single two-pointer pass.
- Space — O(n): the output array (O(1) beyond it).
Common Pitfalls
- Fill the result from the back. The two-pointer walk produces the largest square first, so writing forward puts the biggest value at index 0 and gives
100 0 1 9 16instead of0 1 9 16 100. - Compare absolute values, not raw values. The largest square sits at whichever end is furthest from zero, which on an array with negatives is the left end -- comparing raw values picks the wrong end and returns
16 1 0 9 100.
Full Solution — all languages
class Solution:
def sortedSquares(self, nums):
n = len(nums)
res = [0] * n
lo, hi, k = 0, n - 1, n - 1
while lo <= hi:
if abs(nums[lo]) > abs(nums[hi]):
res[k] = nums[lo] * nums[lo]
lo += 1
else:
res[k] = nums[hi] * nums[hi]
hi -= 1
k -= 1
return resimport java.util.*;
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int lo = 0, hi = n - 1, k = n - 1;
while (lo <= hi) {
if (Math.abs(nums[lo]) > Math.abs(nums[hi])) {
res[k] = nums[lo] * nums[lo];
lo++;
} else {
res[k] = nums[hi] * nums[hi];
hi--;
}
k--;
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> sortedSquares(vector<int>& nums) {
int n = (int)nums.size();
vector<int> res(n);
int lo = 0, hi = n - 1, k = n - 1;
while (lo <= hi) {
if (abs(nums[lo]) > abs(nums[hi])) {
res[k] = nums[lo] * nums[lo];
lo++;
} else {
res[k] = nums[hi] * nums[hi];
hi--;
}
k--;
}
return res;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var sortedSquares = function(nums) {
const n = nums.length;
const res = new Array(n);
let lo = 0, hi = n - 1, k = n - 1;
while (lo <= hi) {
if (Math.abs(nums[lo]) > Math.abs(nums[hi])) {
res[k] = nums[lo] * nums[lo];
lo++;
} else {
res[k] = nums[hi] * nums[hi];
hi--;
}
k--;
}
return res;
};