Squaring A Sorted Array
Two Pointers
Problem
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.
Solution
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
squareArray = [0 for i in range(len(A))]
i = 0
j = len(A)-1
highestIndex = len(A)-1
while i <= j:
leftSquare = A[i]*A[i]
rightSquare = A[j]*A[j]
if rightSquare >= leftSquare:
squareArray[highestIndex] = rightSquare
j-=1
else:
squareArray[highestIndex] = leftSquare
i+=1
highestIndex-=1
return squareArray
Last updated
Was this helpful?