squares of a sorted array in python

Solutions on MaxInterview for squares of a sorted array in python by the best coders in the world

showing results for - "squares of a sorted array in python"
Camden
30 Feb 2019
1class SquaresIterator(object):
2    def __init__(self, sorted_array):
3        self.sorted_array = sorted_array
4        self.left_pointer = 0
5        self.right_pointer = len(sorted_array) - 1
6    
7    def __iter__(self):
8        return self
9    
10    def __next__(self):
11        if self.left_pointer > self.right_pointer:
12            raise StopIteration
13        left_square = self.sorted_array[self.left_pointer] ** 2
14        right_square = self.sorted_array[self.right_pointer] ** 2
15        if left_square > right_square:
16            self.left_pointer += 1
17            return left_square
18        else:
19            self.right_pointer -= 1
20            return right_square
21     
22
23class Solution:
24    def sortedSquares(self, A: List[int]) -> List[int]:
25        return_array = [0] * len(A)
26        write_pointer = len(A) - 1
27        for square in SquaresIterator(A):
28            return_array[write_pointer] = square
29            write_pointer -= 1
30        return return_array
31