The Squares of a Sorted Array coding problem asks you to take an array of integers that is already sorted in non-decreasing order and return a new array containing the squares of each number, also sorted in non-decreasing order. The main challenge arises from the presence of negative numbers, whose squares become positive and can potentially be larger than the squares of positive numbers later in the array.
This "Easy" problem is a staple at companies like Apple, Uber, and Microsoft. It's designed to see if a candidate can optimize beyond a simple sorting approach. While you could just square everything and sort it, interviewers are looking for a linear solution that takes advantage of the fact that the original array is already sorted. It tests your ability to use the Two Pointers interview pattern effectively.
The optimal Algorithmic pattern used here is Two Pointers. Since the largest squares must come from either the very beginning (large negative numbers) or the very end (large positive numbers) of the sorted array, you place one pointer at the start and one at the end. You compare the absolute values (or the squares) of the elements at these pointers, place the larger one at the end of your result array, and move the corresponding pointer inward.
Suppose you have the array [-4, -1, 0, 3, 10].
Whenever you have a sorted array and are asked to produce another sorted array based on some transformation of the values, always consider the Two Pointers interview pattern. It's the most common way to achieve linear time complexity in such scenarios.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sort Array By Parity | Easy | Solve | |
| Merge Sorted Array | Easy | Solve | |
| Sort Array By Parity II | Easy | Solve | |
| Minimum Average of Smallest and Largest Elements | Easy | Solve | |
| 3Sum Closest | Medium | Solve |