Back to articles
Squares of a Sorted Array

Squares of a Sorted Array

via Dev.to BeginnersJeyaprasad R

In this task, I worked on converting a sorted array into another sorted array of their squares. The tricky part is that even though the input array is sorted, squaring negative numbers can mess up the order. For example, -4² = 16 which is bigger than 3² = 9 . What I Did I created a function sortedSquares that takes a sorted array nums and returns a new sorted array of squared values. How I Solved It Instead of squaring everything and sorting again, I used a two-pointer approach . I used three variables: left starting from the beginning (index 0) right starting from the end (index n-1) pos to fill the result array from the back At each step: I compare the absolute values of nums[left] and nums[right] The larger absolute value will give the larger square I place that square at the current pos in the result array Then move the corresponding pointer ( left or right ) Decrease pos to fill the next position This way, I build the sorted squared array from the back. Code class Solution : def s

Continue reading on Dev.to Beginners

Opens in a new tab

Read Full Article
7 views

Related Articles