← All problems

Squares of a Sorted Array

Easy arrayssortingtwo-pointers LeetCode ↗
Given an integer array sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order. Squaring breaks the order because large negatives become large positives — but you can still do this in O(n) without a general sort.

Hints (0/3 revealed)

Log in to reveal hints progressively.

Complexity

Time O(n), space O(n) for the output.

Common pitfalls

  • Squaring then calling sort — O(n log n) misses the intended linear solution.
  • Filling the result front-to-back, which reverses the order.
  • Integer overflow in languages with fixed-width ints (not an issue in Python).

Your solution

Log in to save your code and track progress.