Forem

Tanishka V
Tanishka V

Posted on

ASSIGNMENT 18

๐Ÿ“Œ Problem Statement

Given a sorted integer 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]
Enter fullscreen mode Exit fullscreen mode

Example 2

Input:  [-7, -3, 2, 3, 11]
Output: [4, 9, 9, 49, 121]
Enter fullscreen mode Exit fullscreen mode

โ— Why Not Just Square & Sort?

A simple solution:

square โ†’ sort
Enter fullscreen mode Exit fullscreen mode

But that takes:

  • โฑ O(n log n) time

๐Ÿ‘‰ We can do better: O(n)


๐Ÿ’ก Optimal Approach: Two-Pointer Technique

๐Ÿง  Key Insight

  • The array is sorted, BUT contains negative numbers
  • Squaring negatives makes them positive โ†’ order breaks

๐Ÿ‘‰ The largest square will always come from:

  • Either the leftmost element OR
  • The rightmost element

๐Ÿ”„ Algorithm Steps

  1. Initialize:
   left = 0
   right = n - 1
Enter fullscreen mode Exit fullscreen mode
  1. Create result array of size n
  2. Fill from end to start
  3. Compare:
  • abs(nums[left]) vs abs(nums[right])
    1. Place the larger square at the end

๐Ÿ’ป Python Implementation

```python id="code1"
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
Enter fullscreen mode Exit fullscreen mode

Example usage

nums = [-4, -1, 0, 3, 10]
print(sorted_squares(nums))




---

## ๐Ÿงพ Output



```id="out1"
[0, 1, 9, 16, 100]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Dry Run (Quick Insight)

For:

[-4, -1, 0, 3, 10]
Enter fullscreen mode Exit fullscreen mode
  • Compare |-4| and |10|
  • Place 100 at end
  • Move inward and repeat

โšก Complexity Analysis

Metric Value
Time Complexity O(n)
Space Complexity O(n)

๐ŸŽฏ Key Takeaways

  • Sorting after squaring is not optimal โŒ
  • Use two-pointer technique for O(n) โœ…
  • Works because input array is already sorted ๐Ÿ”ฅ

๐Ÿ Conclusion

This problem is a great example of how understanding the data structure can lead to optimized solutions.


Top comments (0)