Squaring a Sorted Array with Optimized Two Pointer Approach

🚀 Day 13/100 – LeetCode Journey Today’s problem: Squares of a Sorted Array 🔥 Approach 1 (Brute Force + Sorting) 👉 Workflow: Square every element Store in new array Sort the array ⚡ Time Complexity: O(n log n) (because of sorting) 💡 Approach 2 (Two Pointer – Optimized) 👉 Workflow: Use two pointers (left, right) Compare squares of both ends Place larger square at the end of result array Move pointers accordingly ⚡ Time Complexity: O(n) 🧠 Why Optimized is Better? Original array is already sorted But after squaring, order may break (because negatives become positive) 👉 Example: [-4, -1, 0, 3, 10] Squares → [16, 1, 0, 9, 100] ❌ not sorted Sorting again → O(n log n) Two-pointer uses property of sorted array → O(n) 👉 We compare largest absolute values from ends instead of sorting 🧠 Key Insight: Largest square always comes from either: leftmost (large negative) or rightmost (large positive) 🧠 Space Complexity: O(n) (result array) Learning optimization step by step 🚀 #100DaysOfCode #LeetCode #DSA #Java

  • text

To view or add a comment, sign in

Explore content categories