977. Squares of a Sorted Array
🟩 Easy
Question
Input: [-4,-1,0,3,10], [-7,-3,2,3,11]
Output: [0,1,9,16,100], [4,9,9,49,121]Two Pointer Approach
def sortedSquares(self, A: List[int]) -> List[int]:
B = [0] * len(A)
k = len(B) - 1
i, j = 0, len(A) - 1
while (i <= j):
#compare squares before add to result array
I = A[i] * A[i]
J = A[j] * A[j]
if I < J:
B[k] = J
j -= 1
else:
B[k] = I
i += 1
k -= 1
return BSort
Last updated