Squares of a Sorted Array — LeetCode 977 Python Solution

EasyArrayTwo PointersSorting
Problem
#977
Reading time
3 min

The problem

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example

Input
nums = [-4,-1,0,3,10]
Output
[0,1,9,16,100]
Explanation
After squaring, the array becomes [16,1,0,9,100].

Python solution

Python
class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        ans = []
        i, j = 0, len(nums) - 1
        while i <= j:
            a = nums[i] * nums[i]
            b = nums[j] * nums[j]
            if a > b:
                ans.append(a)
                i += 1
            else:
                ans.append(b)
                j -= 1
        return ans[::-1]

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 977. Squares of a Sorted Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 977. Squares of a Sorted Array?
LeetCode 977. Squares of a Sorted Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 977. Squares of a Sorted Array?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 977. Squares of a Sorted Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 977. Squares of a Sorted Array cover?
LeetCode 977. Squares of a Sorted Array is tagged Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview