Community Problem

Squares of a Sorted Array

Difficulty: Easy

Return the squares of a sorted integer array, also sorted, in O(n) time using a two-pointer merge from the ends.

Squares of a Sorted Array

Return the squares of a sorted integer array, also sorted, in O(n) time using a two-pointer merge from the ends.

EASY
Free
arrays
two-pointers
sorting
imanichen

By @imanichen

January 27, 2026

·

Updated May 18, 2026

1,186 views

22

4.5 (11)

Showed up in a phone screen for a junior role last month and I have stolen it as my warmup ever since, because the obvious O(n log n) sort answer is the wrong one and the interviewer is patiently waiting for the candidate to realize the input is already sorted. The trick is that squaring breaks monotonicity for negative values but the largest absolute values still live at the two ends, which is exactly the setup the two-pointer merge wants.

Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order.

Examples

Example 1:

  • Input: nums = [-4, -1, 0, 3, 10]
  • Output: [0, 1, 9, 16, 100]
  • Explanation: After squaring, [16, 1, 0, 9, 100], which sorts to [0, 1, 9, 16, 100].

Example 2:

  • Input: nums = [-7, -3, 2, 3, 11]
  • Output: [4, 9, 9, 49, 121]
  • Explanation: Two of the inputs square to the same value (9). The output keeps both copies.

Example 3:

  • Input: nums = [0, 1, 2, 3]
  • Output: [0, 1, 4, 9]
  • Explanation: All non-negative inputs already give a sorted square array.

Example 4:

  • Input: nums = [-5, -4, -3]
  • Output: [9, 16, 25]
  • Explanation: All non-positive inputs reverse direction after squaring.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order.

Follow-up

The straightforward O(n log n) solution is to square every element and call sort. Can you do it in O(n) time, taking advantage of the sorted input?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems