Skip to main content

Squares of a Sorted Array

LeetCode 1019 | Difficulty: Easy​

Easy

Problem Description​

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 10^4`

- `-10^4 <= nums[i] <= 10^4`

- `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?

Topics: Array, Two Pointers, Sorting


Approach​

Two Pointers​

Use two pointers to traverse the array, reducing the search space at each step. This avoids the need for nested loops, bringing complexity from O(nΒ²) to O(n) or O(n log n) if sorting is involved.

When to use

Array is sorted or can be sorted, and you need to find pairs/triplets that satisfy a condition.


Solutions​

Solution 1: C# (Best: 152 ms)​

MetricValue
Runtime152 ms
Memory48.7 MB
Date2022-01-13
Solution
public class Solution {
public int[] SortedSquares(int[] nums) {
int[] result = new int[nums.Length];
int l = 0, r = nums.Length-1;
int counter = nums.Length -1;
while(l <=r)
{
if(Math.Abs(nums[l])>Math.Abs(nums[r]))
{
result[counter] = nums[l] * nums[l];
l++;
}
else
{
result[counter] = nums[r] * nums[r];
r--;
}
counter--;
}
return result;
}
}

Complexity Analysis​

ApproachTimeSpace
Two Pointers$O(n)$$O(1)$
Sort + Process$O(n log n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Ask: "Can I sort the array?" β€” Sorting often enables two-pointer techniques.