Squares of a Sorted Array - Leetcode Solution


Step-by-Step Thought Process

Brute Force

  1. Understand the problem: Given a sorted array of integers, return a new array containing the squares of each number in non-decreasing order.
  2. Get the length n of the input array nums.
  3. Iterate through each index i from 0 to n-1.
  4. Replace nums[i] with its square (nums[i] ** 2).
  5. Sort the modified array nums in non-decreasing order.
  6. Return nums as the sorted array of squares.

Code Solution (Brute Force)


                

                

                

                

Why the Brute-Force Solution is Inefficient

The brute-force solution squares each element and then sorts the entire array, leading to:

Optimal Solution

The optimal solution uses two pointers to build the result in O(n) time by comparing absolute values from both ends:

  1. Initialize two pointers: left to 0 and right to the last index of nums.
  2. Initialize an empty list result to store the squared values.
  3. While left is less than or equal to right, compare the absolute values of nums[left] and nums[right].
  4. If abs(nums[left]) is greater than abs(nums[right]), append nums[left] ** 2 to result and increment left.
  5. Otherwise, append nums[right] ** 2 to result and decrement right.
  6. Reverse the result list to get the squares in non-decreasing order.
  7. Return result as the sorted array of squares.

Code Solution (Optimal)


                

                

                

                

Detailed Explanation

Understanding the Problem: Squares of a Sorted Array

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:

  • Input: [-4, -1, 0, 3, 10] → Output: [0, 1, 9, 16, 100]
  • Input: [-7, -3, 2, 3, 11] → Output: [4, 9, 9, 49, 121]

Why This Problem Matters

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.

Brute Force Approach: Square and Sort

A naive approach is to square each element in the array and then sort the entire array.

Steps:

  1. Iterate through the array and replace each element with its square.
  2. Sort the resulting array in non-decreasing order.
  3. Return the sorted 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.

Optimal Solution: Two-Pointer Technique

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.

Steps:

  1. Initialize two pointers: left = 0, right = nums.length - 1.
  2. Create a result array of the same size, filled with zeroes.
  3. Initialize a pointer pos = nums.length - 1 to fill the result array from the end.
  4. While left <= right:
    • If Math.abs(nums[left]) > Math.abs(nums[right]), set result[pos] = nums[left] ** 2 and increment left.
    • Else, set result[pos] = nums[right] ** 2 and decrement right.
    • Decrement pos.
  5. Return the result array.

Example Walkthrough

Input: [-4, -1, 0, 3, 10]

  • left = -4 → 16, right = 10 → 100
  • Compare and place the larger square at the end → 100 goes in last position
  • Repeat until left > right
  • Final result: [0, 1, 9, 16, 100]

Time and Space Complexity

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.)

Edge Cases to Consider

  • All non-negative values → output is simply the squares
  • All non-positive values → reverse the squared values
  • Zeros only → return all zeros
  • Mixed positive and negative numbers → two-pointer logic is essential

Conclusion

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.

Get Personalized Support at AlgoMap Bootcamp 💡