977. Squares of a Sorted Array
Asked at 16Meta55Bloomberg53Google44Amazon43Microsoft38Instacart90Uber89Yandex63tcs54Whatnot78Ozon70CrowdStrike65Deutsche Bank62Adobe44Accenture44Infosys39
Problem
nums is sorted in non-decreasing order and may contain negatives. Return the squares of its values, also sorted.
Example: [-4,-1,0,3,10] → [0,1,9,16,100]
Constraints: follow-up: O(n) without sorting again.
The largest square is at one of the ends. Fill the result from the back, taking the larger |value| each time.
Complexity: O(n).
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums)
res = [0] * n
l, r = 0, n - 1
for k in range(n - 1, -1, -1):
if abs(nums[l]) > abs(nums[r]):
res[k] = nums[l] ** 2; l += 1
else:
res[k] = nums[r] ** 2; r -= 1
return res
assert Solution().sortedSquares([-4, -1, 0, 3, 10]) == [0, 1, 9, 16, 100]
assert Solution().sortedSquares([-7, -3, 2, 3, 11]) == [4, 9, 9, 49, 121]
assert Solution().sortedSquares([-5, -3, -2, -1]) == [1, 4, 9, 25]
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length, l = 0, r = n - 1;
int[] res = new int[n];
for (int k = n - 1; k >= 0; k--) {
if (Math.abs(nums[l]) > Math.abs(nums[r])) { res[k] = nums[l] * nums[l]; l++; }
else { res[k] = nums[r] * nums[r]; r--; }
}
return res;
}
}
func sortedSquares(nums []int) []int {
n := len(nums)
res := make([]int, n)
l, r := 0, n-1
for k := n - 1; k >= 0; k-- { // the biggest square is at one of the ends
if nums[l]*nums[l] > nums[r]*nums[r] {
res[k] = nums[l] * nums[l]
l++
} else {
res[k] = nums[r] * nums[r]
r--
}
}
return res
}