"Sorting Squares of a Sorted Array in Java"

🔍 Problem Statement: Given an integer array sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. 🧠 Key Idea: Since the array is already sorted, negative numbers can affect the order after squaring. To handle this efficiently, I used the two-pointer approach — one starting from the beginning and one from the end — comparing squares and filling the result array from the back. ⚙️ Time Complexity: O(n) 🗂️ Space Complexity: O(n) 💬 Code (Java): import java.util.Arrays; class Solution { public int[] sortedSquares(int[] nums) { int n = nums.length; int[] res = new int[n]; int left = 0, right = n - 1, index = n - 1; while (left <= right) { int lsq = nums[left] * nums[left]; int rsq = nums[right] * nums[right]; if (lsq > rsq) { res[index--] = lsq; left++; } else { res[index--] = rsq; right--; } } return res; } } ✨ Learning: Improved my understanding of two-pointer technique. Reinforced the importance of optimizing sorting-related problems. #Java #DSA #Coding #ProblemSolving #StriversSheet #LearningEveryday

  • graphical user interface

To view or add a comment, sign in

Explore content categories