Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
nums is sorted in non-decreasing order.l=0, r=n-1, and pos=n-1. Compare abs(nums[l]) vs abs(nums[r]). Whichever is larger — square it and place it at result[pos], then advance the winning pointer inward (l++ or r--) and decrement pos. You always fill the result from right to left, largest square first.result[pos] is exactly the right slot for the current maximum.Imagine you have tiles of various sizes lined up in a row, where the smallest tiles are in the middle and the largest are at both ends (the far left and far right). You want to stack them in a new row from smallest to largest. Your strategy: always compare the two outermost tiles, pick the bigger one, place it at the last open slot in your new row, then move inward. This builds the sorted result naturally — largest to smallest from right to left — without needing a separate sorting pass.
The simplest approach is to first map every element in the array to its square. Then, use a built-in sorting algorithm to sort the new array.
nums[i] with nums[i] * nums[i].Why it's not optimal: Sorting takes O(n log n) time. Since the original array is already sorted, we are ignoring a very important constraint we could use to optimize our solution to O(n) time.
def sortedSquares(nums): for i in range(len(nums)): nums[i] *= nums[i] nums.sort() return nums
The input is sorted, so the largest squares are always at the ends. Use two pointers l (left, blue) and r (right, orange). At each step compare abs(nums[l]) vs abs(nums[r]), place the larger square at result[pos], advance the winning pointer inward, and decrement pos.
result = [0]*n, l=0, r=n-1, pos=n-1.l <= r: compare abs(nums[l]) vs abs(nums[r]).abs(l) > abs(r): place nums[l]² at result[pos], l++.nums[r]² at result[pos], r--.pos after each placement. Return result.
Discussion
…