Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Two pointers

Squares of a sorted array, in order

Easy · Target 10 minutes · Two pointers

Given an integer array nums sorted in non-decreasing order, return the squares of its elements, also in non-decreasing order. Do it in O(n) time, without sorting the squares.

Examples

InputOutputWhy
nums = [-4, -1, 0, 3, 10][0, 1, 9, 16, 100]
nums = [-7, -3, 2, 3, 11][4, 9, 9, 49, 121](−3)² and 3² are both 9.

Constraints

  • 1 ≤ n ≤ 10⁴
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • nums is sorted in non-decreasing order

Hints

Hint 1

Squaring and sorting is O(n log n). Where in the array can the largest square be?

Hint 2

The largest square comes from the most negative value or the most positive one: one of the two ends.

Hint 3

Compare the absolute values at the two ends, write the larger square into the last free slot of the result, and move that pointer inward.

Where people lose marks

  • Filling from the front: the smallest square is in the middle somewhere, and finding it costs a search.
  • Comparing the values rather than their absolute values, which puts −7 below 2.
  • Squares of values up to 10⁴ fit a 32-bit integer (10⁸); larger inputs would need 64-bit.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.