This problem is a classic example where a simple idea (squaring numbers) becomes tricky due to negative values.
It teaches how to optimize using the two-pointer technique.
๐ Problem Statement
Given a sorted array nums (in non-decreasing order), return a new array of the squares of each number, also sorted in non-decreasing order.
๐ Examples
Example 1:
Input: [-4, -1, 0, 3, 10]
Output: [0, 1, 9, 16, 100]
Example 2:
Input: [-7, -3, 2, 3, 11]
Output: [4, 9, 9, 49, 121]
๐ง Intuition
Even though the array is sorted, squaring negative numbers makes them positive:
๐ Larger negative numbers can produce larger squares
๐ So the order may break after squaring
Instead of sorting again, we can use a smarter approach.
๐ Approach 1: Brute Force
- Square each element
- Sort the array
๐ป Code:
```python id="sq1"
def sorted_squares(nums):
return sorted([x * x for x in nums])
โก Complexity:
* Time: O(n log n)
* Space: O(n)
---
๐ Approach 2: Two-Pointer (Optimal)
Step-by-Step:
1. Use two pointers:
* `left = 0`
* `right = n - 1`
2. Create a result array of same size
3. Compare squares:
* Place the larger square at the end
* Move the corresponding pointer
4. Fill array from back to front
---
๐ป Python Code
```python id="sq2"
def sorted_squares(nums):
n = len(nums)
result = [0] * n
left = 0
right = 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
print(sorted_squares([-4, -1, 0, 3, 10]))
๐งพ Dry Run
For: nums = [-4, -1, 0, 3, 10]
Steps:
- Compare |-4| and |10| โ 100 โ place at end
- Compare |-4| and |3| โ 16
- Compare |-1| and |3| โ 9
- Compare |-1| and |0| โ 1
- Compare |0| and |0| โ 0
Final: [0, 1, 9, 16, 100]
โก Complexity
Time Complexity: O(n)
Space Complexity: O(n)
๐ฅ Why This Works
- Uses sorted property of array
- Avoids extra sorting
- Efficient linear traversal
โ ๏ธ Edge Cases
- All negative numbers
- All positive numbers
- Single element array
๐ Conclusion
This problem shows how:
- Brute force can be improved
- Two-pointer technique optimizes performance
- Understanding patterns is key in DSA
Top comments (0)