
Squares of a Sorted Array
Introduction When working with sorted arrays, problems often require maintaining order after performing operations. One such problem is squaring each element and returning the result in sorted order. At first glance, it may seem simple, but handling negative numbers makes it interesting. Problem Statement Given a sorted array nums in non-decreasing order, return a new array containing the squares of each number, also sorted in non-decreasing order. Example 1 Input: nums = [ - 4 , - 1 , 0 , 3 , 10 ] Output: [ 0 , 1 , 9 , 16 , 100 ] Explanation: After squaring → [16, 1, 0, 9, 100] After sorting → [0, 1, 9, 16, 100] Example 2 Input: nums = [ - 7 , - 3 , 2 , 3 , 11 ] Output: [ 4 , 9 , 9 , 49 , 121 ] Two-Pointer Approach We use: left → start of array right → end of array Fill result from the end Steps Compare absolute values of nums[left] and nums[right] Place the larger square at the end Move the corresponding pointer Repeat until done Python Implementation def sorted_squares ( nums ): n =
Continue reading on Dev.to Python
Opens in a new tab
![[Learning notes and hw] getting started with R-cnn: Manually implementing Intersection over Union (IoU)](/_next/image?url=https%3A%2F%2Fmedia2.dev.to%2Fdynamic%2Fimage%2Fwidth%3D800%252Cheight%3D%252Cfit%3Dscale-down%252Cgravity%3Dauto%252Cformat%3Dauto%2Fhttps%253A%252F%252Fdev-to-uploads.s3.amazonaws.com%252Fuploads%252Farticles%252Favit2emoxc0g68e5ltqj.jpg&w=1200&q=75)



