Back to Dashboard
Squaring Sorted Array
EasyProblem Statement
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Examples
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]
Approach 1: Two Pointers
O(n)
O(n)
// The greatest will be either in the first or at the end, so we will fill it from the end.
class Solution {
public int[] sortedSquares(int[] nums) {
var l = 0;
var r = nums.length - 1;
var out = new int[nums.length];
var k = nums.length - 1;
while (l <= r) {
if (Math.abs(nums[l]) > Math.abs(nums[r])) {
out[k] = nums[l] * nums[l];
l ++;
} else {
out[k] = nums[r] * nums[r];
r --;
}
k --;
}
return out;
}
}