Squares of a Sorted Array - Java Solution

1. Introduction

In this blog post, we will explore a simple yet interesting array processing problem: squaring each number in a sorted array and then returning a new array that is also sorted. This problem is a good test of understanding array manipulation and sorting in Java.

Problem

Given an array of numbers sorted in increasing order, the task is to return a new array containing squares of all the numbers of the input array, sorted in increasing order.

Example 1:

Input: a[] = [-5, -2, -1, 0, 4, 6]

Output: [0, 1, 4, 16, 25, 36]

Example 2:

Input: nums = [-5, -4, -3, -2, -1]

Output: [1, 4, 9, 16, 25]

Example 3:

Input: nums = [1, 2, 3, 4, 5]

Output: [1, 4, 9, 16, 25]

2. Solution Steps

1. Initialize two pointers at the start and end of the array.

2. Create a new array for the result.

3. Compare the absolute values of elements pointed by the two pointers.

4. Square the larger absolute value and put it in the result array.

5. Move the pointers accordingly and repeat until the entire array is processed.

6. Return the result array.

3. Code Program

public class Solution {

    // Main method for testing
    public static void main(String[] args) {
        int[] a1 = {-5, -2, -1, 0, 4, 6};
        int[] a2 = {-5, -4, -3, -2, -1};
        int[] a3 = {1, 2, 3, 4, 5};

        System.out.println("Squared and sorted array: " + Arrays.toString(makeSquares(a1)));
        System.out.println("Squared and sorted array: " + Arrays.toString(makeSquares(a2)));
        System.out.println("Squared and sorted array: " + Arrays.toString(makeSquares(a3)));
    }

    // Method to create a new sorted array of squares
    public static int[] makeSquares(int[] nums) {
        int n = nums.length;
        int[] squares = new int[n];
        int highestSquareIdx = n - 1;
        int left = 0, right = n - 1;

        while (left <= right) {
            int leftSquare = nums[left] * nums[left];
            int rightSquare = nums[right] * nums[right];

            if (leftSquare > rightSquare) {
                squares[highestSquareIdx--] = leftSquare;
                left++;
            } else {
                squares[highestSquareIdx--] = rightSquare;
                right--;
            }
        }

        return squares;
    }
}

Output:

Squared and sorted array: [0, 1, 4, 16, 25, 36]
Squared and sorted array: [1, 4, 9, 16, 25]
Squared and sorted array: [1, 4, 9, 16, 25]

Explanation:

The makeSquares method processes the input array from both ends using two pointers. It squares the numbers and stores them in the result array from the highest index to the lowest, ensuring the result is sorted. 

For example, with the input array [-5, -2, -1, 0, 4, 6], it squares the numbers and arranges them as [0, 1, 4, 16, 25, 36], which is the sorted array of squares.

Comments