Pattern visualizer
Squares of a Sorted Array
The key insight: given a sorted array that may contain negative numbers, the square of a negative number is positive and large in magnitude when the number has large absolute value. Since the array is sorted, the largest square could come from either end (the most negative or the most positive). Use two pointers starting at both ends, compare the squared magnitudes, and fill the result array from the back (largest square first) since either end could hold the largest absolute value. Animated on: Given nums = [-4, -1, 0, 3, 10], return the squares of each number sorted in non-decreasing order. Answer: [0, 1, 9, 16, 100]..
Two Pointers
left = 0, right = n - 1 = 4, pos = n - 1 = 4: initialize two pointers at both ends and a result array position at the back. The squared magnitudes are 16 and 100 respectively.
1FUNCTION sortedSquares(nums):2 n = length of nums3 result = a new array of length n4 left = 0, right = n - 15 pos = n - 16 WHILE left <= right:7 leftSquare = nums[left] * nums[left]8 rightSquare = nums[right] * nums[right]9 IF leftSquare > rightSquare:10 result[pos] = leftSquare11 left = left + 112 ELSE:13 result[pos] = rightSquare14 right = right - 115 pos = pos - 1
← / → step · space play · Home restart