DEV Community

Dharani
Dharani

Posted on

Squares Of a Sorted Array

Introduction

The "Squares of a Sorted Array" problem is a common question that helps us understand arrays and the two-pointer technique.


Problem Statement

Given a sorted array of integers (which may include negative numbers), return a new array of the squares of each number, also sorted in non-decreasing order.


Approach (Two-Pointer Technique)

Since negative numbers become positive after squaring, we use two pointers:

  1. Initialize:

    • left = 0
    • right = n - 1
  2. Compare squares of left and right elements

  3. Place the larger square at the end of result array

  4. Move the corresponding pointer

  5. Repeat until all elements are processed


Python Code


python
def sorted_squares(nums):
    n = len(nums)
    result = [0] * n

    left, right = 0, n - 1
    pos = n - 1

    while left <= right:
        if abs(nums[left]) > abs(nums[right]):
            result[pos] = nums[left] ** 2
            left += 1
        else:
            result[pos] = nums[right] ** 2
            right -= 1
        pos -= 1

    return result

# Example
nums = [-4, -1, 0, 3, 10]
print("Sorted Squares:", sorted_squares(nums))


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

## Output
   [0, 1, 9, 16, 100]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)