
Squares of a Sorted Array Using Two Pointer Technique in Python
Problem Explanation You are given a sorted array nums (in non-decreasing order). Your task is to 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] Input: nums = [-7, -3, 2, 3, 11] Output: [4, 9, 9, 49, 121] Method Used: Two Pointer Technique Idea Even though the array is sorted, negative numbers become large when squared . So we: Compare squares from both ends Place the largest square at the end of result Why This Method? Time complexity: O(n) Space complexity: O(n) Avoids extra sorting Efficient and optimal Python Code with Explanation class Solution : def sortedSquares ( self , nums ): Defines the function. n = len ( nums ) Store the size of the array. result = [ 0 ] * n Create a result array of same size. left = 0 right = n - 1 Initialize two pointers: left at start right at end pos = n - 1 Position where the next largest square will be placed. while left <= right : Loo
Continue reading on Dev.to Python
Opens in a new tab




