Taro Logo

Squares of a Sorted Array

#158 Most AskedEasy
0 views
Topics:
ArraysTwo Pointers

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.
Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array contain negative numbers, and is it guaranteed to be sorted in non-decreasing order initially?
  2. What should we return if the input array is empty or null?
  3. Should the squared values be returned in-place by modifying the original array, or should I allocate a new array for the result?
  4. Are there any constraints on the range of the integer values in the array that could lead to integer overflow when squaring them?
  5. How should duplicate values in the input array be handled in the output?

Brute Force Solution

Approach

Imagine you are given a row of numbers that are already ordered from smallest to largest, and your task is to figure out what those numbers look like after you multiply each of them by themselves. The brute force approach simply looks at every single number one by one, performs the multiplication, and collects all the new resulting values together.

Here's how the algorithm would work step-by-step:

  1. Look at the very first number in the given row.
  2. Multiply that number by itself to find its new squared value.
  3. Take that new squared value and put it into a completely new collection of results.
  4. Move on to the next number in the row and repeat the multiplication process.
  5. Continue doing this for every single number in the row until no numbers are left unexamined.
  6. Once you have gathered all the squared values in your new collection, arrange them so they go from the smallest value to the largest value.
  7. Present this newly sorted collection as your final answer.

Code Implementation

def sorted_squares_brute_force(sorted_numbers):
    squared_collection = []

    # Square every individual number so we can collect all transformed values
    for current_number in sorted_numbers:
        squared_value = current_number * current_number
        squared_collection.append(squared_value)

    # Sort the collection because squaring negative numbers disrupts the original order
    squared_collection.sort()

    return squared_collection

Big(O) Analysis

Time Complexity
O(n log n) – For each of the n elements in the array, we perform a multiplication to find its square and store it in a new collection. Once all n values are gathered, we must sort the new collection, which takes n log n time. The cost is driven by visiting every element once for squaring and then applying a sorting algorithm to the entire set of n squared values. Combining the linear squaring step and the logarithmic sorting step yields approximately n + n log n total operations, which simplifies to O(n log n).
Space Complexity
O(N) – The brute force approach described in the steps creates a completely new collection of results to gather every squared value. Specifically, it allocates an auxiliary array or list of size N to store these intermediate squared results before sorting them. As the input size N grows, the memory required for this new collection scales linearly. Therefore, the total auxiliary space complexity simplifies to O(N).

Optimal Solution

Approach

Instead of squaring all the numbers first and trying to sort them from scratch, the optimal approach works backwards by comparing the most extreme values. Since the biggest squared numbers will always be sitting at the very beginning or the very end of the line, we can simply pick the larger one, place it into its final spot, and move inward.

Here's how the algorithm would work step-by-step:

  1. Look at the numbers sitting at the far left and the far right ends of the line.
  2. Square both of these numbers to see which one produces a larger value.
  3. Take the larger squared value and place it into the very last available spot in a brand new line.
  4. Move your attention inward from the side where you just took the winning number.
  5. Repeat this comparison and placement process, filling up your new line from the back to the front.
  6. Continue this inward march until all the numbers have been squared and placed in their proper positions.

Code Implementation

def sorted_squares(sorted_numbers):
    array_length = len(sorted_numbers)
    result_array = [0] * array_length
    left_pointer = 0
    right_pointer = array_length - 1
    insertion_index = array_length - 1

    # Compare outer extremes because the largest squares always reside at the array ends.
    while left_pointer <= right_pointer:
        left_square = sorted_numbers[left_pointer] ** 2
        right_square = sorted_numbers[right_pointer] ** 2

        # Place the larger square at the current end and shrink the active boundary.
        if left_square > right_square:
            result_array[insertion_index] = left_square
            left_pointer += 1
        else:
            result_array[insertion_index] = right_square
            right_pointer -= 1

        insertion_index -= 1

    # Return the fully populated array containing sorted squared values.
    return result_array

Big(O) Analysis

Time Complexity
O(n) – We use a single two-pointer approach that starts at the left and right ends of the array, moving inward until both pointers meet in the middle. During each step, we perform a constant number of comparisons and arithmetic operations to place one squared number into our result array. Because every element is visited and processed exactly once, the total number of operations grows linearly with the input size n. This results in approximately n operations, which simplifies in Big O notation to O(n).
Space Complexity
O(N) – To construct the final sorted result, the algorithm allocates a brand new result array of size N, where N represents the total number of elements in the input array. Beyond this output array, only a few constant-space pointers are maintained for the left, right, and insertion positions. As the input size scales, the auxiliary memory consumed by the new array grows linearly with N. Therefore, simplifying these components to Big O notation yields O(N) auxiliary space complexity.

Edge Cases

Empty input array
How to Handle:
Return the empty array immediately without entering the two-pointer loop.
Array with a single element
How to Handle:
The loop processes the single element, squares it, and returns a new array with that single squared value.
Array containing all negative numbers
How to Handle:
The two-pointer approach correctly starts from the largest absolute values at the left and populates the result array from right to left in ascending order.
Array containing all positive numbers
How to Handle:
The right pointer starts at the end with the largest value, and the pointers move inward while filling the result array correctly.
Array containing zeros
How to Handle:
Zeros square to zero and are handled naturally by the pointer comparisons without causing division by zero or index out of bounds.
Array with mixed positive and negative numbers containing duplicates of absolute values
How to Handle:
The equal condition in the two-pointer comparison safely processes either the negative or positive duplicate first while maintaining correct output order.
Maximum-sized inputs with extreme boundary integer values
How to Handle:
The algorithm scales efficiently in linear O(N) time using two pointers, though squaring the minimum 32-bit signed integer requires 64-bit integers to prevent overflow.
0/257 completed