Squares Of A Sorted Array Problem
Description
LeetCode Problem 977.
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Example 2:
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 in non-decreasing order.
Solution
Approach: Two Pointers from Both Ends
Squaring every number and sorting takes O(n log n). The input is already sorted, which gives an O(n) way.
The squares are not sorted because negative numbers flip: -4 comes before -1, but 16 > 1. Still, the largest square always comes from one of the two ends of the array: the most negative number on the left or the largest number on the right. Everything in between has a smaller absolute value than one of the ends.
So build the result from the back:
- Put
leftat index0andrightat indexn - 1. - For each position from
n - 1down to0, compareabs(nums[left])andabs(nums[right]). Write the square of the larger one at this position and move that pointer inward. - Stop when every position is filled; the pointers meet at the smallest absolute value, which lands at the front.
Example with nums = [-4,-1,0,3,10]: 10 beats -4 (write 100), then -4 beats 3 (write 16), then 3 beats -1 (write 9), then -1 beats 0 (write 1), and finally 0.
Filling from the back is the part that makes it simple. Starting from the front would need to find where the negatives end, the smallest absolute value, and then merge outward.
Complexity: O(n) time and O(n) space for the output, where n is the length of nums.
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums)
result = [0] * n
left, right = 0, n - 1
# The largest square is always at one of the two ends; fill the result from the back.
for position in range(n - 1, -1, -1):
if abs(nums[left]) > abs(nums[right]):
result[position] = nums[left] * nums[left]
left += 1
else:
result[position] = nums[right] * nums[right]
right -= 1
return result