DEV Community

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)