The brute-force solution squares each element and then sorts the entire array, leading to:
The optimal solution uses two pointers to build the result in O(n) time by comparing absolute values from both ends:
The “Squares of a Sorted Array” problem asks you to return an array of the squares of each number in a given sorted array, with the result sorted in non-decreasing order.
For example:
[-4, -1, 0, 3, 10]
→ Output: [0, 1, 9, 16, 100]
[-7, -3, 2, 3, 11]
→ Output: [4, 9, 9, 49, 121]
This problem helps reinforce understanding of array traversal and two-pointer strategies. It's especially valuable because it teaches how to exploit the structure of a sorted array to avoid unnecessary sorting operations.
A naive approach is to square each element in the array and then sort the entire array.
While simple, this method does not make use of the fact that the input array is already sorted, and sorting introduces unnecessary computational overhead.
Since the array is sorted, negative numbers appear on the left and positive numbers on the right. Squaring both can disrupt the order — for example, -4
becomes 16
, which is larger than 3 ** 2 = 9
.
We can use two pointers — one at the start and one at the end — to compare the absolute values and insert the larger square at the end of the result array, moving inward.
left = 0
, right = nums.length - 1
.pos = nums.length - 1
to fill the result array from the end.left <= right
:
Math.abs(nums[left]) > Math.abs(nums[right])
, set result[pos] = nums[left] ** 2
and increment left
.result[pos] = nums[right] ** 2
and decrement right
.pos
.
Input: [-4, -1, 0, 3, 10]
[0, 1, 9, 16, 100]
Time Complexity: O(n), where n is the number of elements in the array. Each element is processed once.
Space Complexity: O(n) for the result array. (If in-place modification is required and allowed, space can be improved depending on constraints.)
The “Squares of a Sorted Array” problem is a great demonstration of how to leverage sorted data to improve performance. By using a two-pointer approach, you can solve the problem in linear time without relying on sorting — making your solution both efficient and elegant.