SDE & MLE Prep

977. Squares of a Sorted Array

Problem

nums is sorted in non-decreasing order and may contain negatives. Return the squares of its values, also sorted.

Example: [-4,-1,0,3,10] → [0,1,9,16,100]

Constraints: follow-up: O(n) without sorting again.

The largest square is at one of the ends. Fill the result from the back, taking the larger |value| each time.

Complexity: O(n).

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        n = len(nums)
        res = [0] * n
        l, r = 0, n - 1
        for k in range(n - 1, -1, -1):
            if abs(nums[l]) > abs(nums[r]):
                res[k] = nums[l] ** 2; l += 1
            else:
                res[k] = nums[r] ** 2; r -= 1
        return res