Introduction
The "Squares of a Sorted Array" problem is a common question that helps us understand arrays and the two-pointer technique.
Problem Statement
Given a sorted array of integers (which may include negative numbers), return a new array of the squares of each number, also sorted in non-decreasing order.
Approach (Two-Pointer Technique)
Since negative numbers become positive after squaring, we use two pointers:
-
Initialize:
- left = 0
- right = n - 1
Compare squares of left and right elements
Place the larger square at the end of result array
Move the corresponding pointer
Repeat until all elements are processed
Python Code
python
def sorted_squares(nums):
n = len(nums)
result = [0] * n
left, right = 0, n - 1
pos = n - 1
while left <= right:
if abs(nums[left]) > abs(nums[right]):
result[pos] = nums[left] ** 2
left += 1
else:
result[pos] = nums[right] ** 2
right -= 1
pos -= 1
return result
# Example
nums = [-4, -1, 0, 3, 10]
print("Sorted Squares:", sorted_squares(nums))
## Input
[-4, -1, 0, 3, 10]
## Output
[0, 1, 9, 16, 100]
Top comments (0)