
# Sorted Squares of a Sorted Array (Java) – Efficient Two-Pointer Approach
When working with sorted arrays, a seemingly simple transformation—like squaring each element—can break the order. This problem is a great example of how understanding patterns in data can help us design efficient algorithms. 🚀 Problem Statement Given an integer array nums sorted in non-decreasing order , return a new array containing the squares of each number , also sorted in non-decreasing order. 👉 Example Input: nums = [- 4 , - 1 , 0 , 3 , 10 ] Output: [ 0 , 1 , 9 , 16 , 100 ] 🤔 Why Is This Tricky? At first glance, you might think: “Just square every element and the array stays sorted.” But that’s not true because: Negative numbers become positive when squared A large negative number (e.g., -10 ) becomes larger than smaller positives when squared Example: [- 7 , - 3 , 2 , 3 , 11 ] → Squares → [ 49 , 9 , 4 , 9 , 121 ] ❌ Not sorted 💡 Key Insight The largest square value will always come from: Either the leftmost element (most negative), or The rightmost element (largest positive) 👉 T
Continue reading on Dev.to
Opens in a new tab



