Skip to main content

Squares of a Sorted Array

Question

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

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

Solution

all//Squares of a Sorted Array.py


def squaresOfSortedArray(arr):
for i in range(len(arr)):
arr[i] = arr[i]*arr[i]
arr.sort()
return arr

# test
arr = [-6, -4, 1, 2, 3, 5]
print(squaresOfSortedArray(arr)) # [1, 4, 9, 16, 25, 36]