Skip to content
Problem 977 · LeetCode 977(opens in a new tab)

Squares of a Sorted Array

EasyArrays

You are given an array nums of integers sorted from smallest to largest. Some of them may be negative.

Square every number and return the squares, also sorted from smallest to largest.

Example 1

Input:  nums = [-6, -1, 0, 2, 4]
Output: [0, 1, 4, 16, 36]
Why:    -6 is the smallest number but has the largest square
2 more examples and the constraints

Example 2

Input:  nums = [-5, -3, 3, 8]
Output: [9, 9, 25, 64]
Why:    -3 and 3 have the same square, 9

Example 3

Input:  nums = [-9, -4, -2]
Output: [4, 16, 81]
Why:    all negative, so the order fully reverses

Constraints

  • 1 ≤ length of nums ≤ 10,000
  • −10,000 ≤ nums[i] ≤ 10,000
  • nums is sorted in non-decreasing order

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Square, then sortO(n log n)
  2. Two pointers from the endsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 numbersVerdict
Square, then sortO(n log n)
Simple; misses the sorted input
Two pointers from the endsO(n)
Best; one pass

n = the length of nums.

Edge cases to test

  • All negative. [-9, -4, -2] gives [4, 16, 81]: the left end wins every time.
  • All non-negative. [1, 2, 6, 9] is already in order; the right end wins every time.
  • Equal absolute values. [-5, -3, 3, 8] has -3 and 3, both 9. Either can go first; the result is the same.
  • A single element. [-7] gives [49]: left and right start on the same index.

Common mistakes

  • Filling result from the front, which needs the smallest square, and that can be anywhere in the middle.
  • Comparing nums[left] > nums[right] instead of their absolute values (or their squares).
  • Stopping the loop when left == right and skipping the last element.

How to talk through it

  1. 1Clarify. Can the array hold negatives and zeros? Should duplicates stay? Is an O(n) answer expected?
  2. 2Give the simple answer. Square everything and sort: O(n log n).
  3. 3Spot the structure. After squaring, the values fall toward zero from both ends, so the biggest is always at an end.
  4. 4Code the pointers. Compare the two ends, write the bigger square at the back, move that pointer in.
  5. 5Test out loud. Run all negative, all positive, a single element and a pair like -3 and 3.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?