SQUARES OF A SORTED ARRAY

 

Squares of a Sorted Array – Two Pointer Approach

Introduction

In this problem, we are given a sorted array that may contain both negative and positive numbers. We need to return a new array containing the squares of each number, also sorted in non-decreasing order.

At first glance, it looks like a simple problem, but squaring negative numbers changes their order.

Problem Statement

Given a sorted array nums[], return a new array containing:

  • Squares of all elements

  • Sorted in non-decreasing order

Example

Input:

nums = [-4, -1, 0, 3, 10]

Output:

[0, 1, 9, 16, 100]

Solution Code

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] ans = new int[nums.length];
        int left = 0; 
        int right = nums.length - 1;
        int ans_pointer = nums.length - 1;

        while (left <= right) {
            int ls = nums[left] * nums[left];
            int rs = nums[right] * nums[right];

            if (ls > rs) {
                ans[ans_pointer] = ls;
                left++;
            } else {
                ans[ans_pointer] = rs;
                right--;
            }
            ans_pointer--;
        }

        return ans;
    }
}

Approach Used: Two Pointer Technique

Idea

Even though the array is sorted:

  • Negative numbers when squared become large positive numbers

So the largest squares will be at either end of the array.

How It Works

  1. Initialize:

    • left = 0 (start of array)

    • right = n - 1 (end of array)

    • ans_pointer = n - 1 (fill result from end)

  2. Compare squares:

    • If left square > right square
       place it at ans_pointer, move left

    • Else
       place right square, move right

  3. Decrease ans_pointer each time

Why This Approach Was Chosen

  • Uses the sorted property of input

  • Avoids sorting again after squaring

  • Works in a single pass (O(n))

Alternative Approach

  • Square all elements and then sort

Arrays.sort(nums);

 Time Complexity: O(n log n)

Why not used?
Because we can do better using two pointers in O(n)

Time and Space Complexity

  • Time Complexity: O(n)

  • Space Complexity: O(n) (for output array)

Important Observation

  • The largest square always comes from either the leftmost or rightmost element

  • Filling the result array from the end ensures correct order

Conclusion

The two-pointer approach efficiently solves the problem by leveraging the sorted nature of the input array. Instead of sorting again, we compare squares from both ends and build the result in linear time, making it the optimal solution.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT