Skip to content
BytePatterns

Squares of a Sorted List

EasyArrays#two-pointers#merge-from-back~15m

Problem

A list of integers is sorted in non-decreasing order and may contain negative values. Return a new list holding the square of every value, also in non-decreasing order. Squaring and then sorting takes O(n log n) time; the goal is O(n) by using the order the input already has.

Examples

Input:  nums = [-5, -2, 1, 3, 4]
Output: [1, 4, 9, 16, 25]
Why:    -5 is the smallest value but gives the largest square
Input:  nums = [-7, -3, -2]
Output: [4, 9, 49]
Why:    all negative, so the squares come out in reverse order
Input:  nums = []
Output: []
Why:    edge case, nothing to square

Hints

0 / 3

Stuck on the idea rather than the code? Merge Sorted Arrays covers it.