DEV Community

Navin S
Navin S

Posted on

๐ŸŸฆ Squares of a Sorted Array (Two-Pointer Approach Explained)

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

  1. Square each element
  2. 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]))
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ 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)