diff --git a/diagonal_traverse.py b/diagonal_traverse.py new file mode 100644 index 00000000..668c6161 --- /dev/null +++ b/diagonal_traverse.py @@ -0,0 +1,49 @@ +''' +Time complexity: O(N*M) +Space complexity: O(N*M) +''' + +class Solution: + def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]: + rows = len(mat) + cols = len(mat[0]) + res = [] + going_up = True # false meaning we are going down + i = j = 0 + + while len(res) != rows * cols: + if going_up: + + while i>=0 and j=0: + res.append(mat[i][j]) + i +=1 + j -=1 + + if i == rows: + j += 2 + i -= 1 + elif j < 0: + j +=1 + + going_up = True + + return res + + + + + + + \ No newline at end of file diff --git a/product_of_array_except_self.py b/product_of_array_except_self.py new file mode 100644 index 00000000..e905c407 --- /dev/null +++ b/product_of_array_except_self.py @@ -0,0 +1,19 @@ +''' +Time: Big O(N) +Space: Big O(1) since result array is not considered as extra space +''' +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + prefix_product = 1 + res = [1]*len(nums) + + for i in range(1,len(nums)): + res[i] = nums[i-1] * prefix_product + prefix_product = res[i] + prefix_product = 1 + + for j in range(len(nums)-2,-1,-1): + res[j] = res[j] * nums[j+1] * prefix_product + prefix_product = nums[j+1] * prefix_product + + return res \ No newline at end of file diff --git a/spiral_traversal.py b/spiral_traversal.py new file mode 100644 index 00000000..3f354010 --- /dev/null +++ b/spiral_traversal.py @@ -0,0 +1,38 @@ +''' +Time complexity: O(N) +Space complexity: O(N) +''' +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + res = [] + if not matrix: + return res + top, bottom = 0, len(matrix) - 1 + left, right = 0, len(matrix[0]) - 1 + + while top <= bottom and left <= right: + + #moving right + for i in range(left, right + 1): + res.append(matrix[top][i]) + top += 1 + + #moving down + for i in range(top, bottom + 1): + res.append(matrix[i][right]) + right -= 1 + + #stop the loop if its a 1 xN or Nx1 matrix + if top > bottom or left > right: + break + # move left + for i in range(right, left - 1, -1): + res.append(matrix[bottom][i]) + bottom -= 1 + + #move up + for i in range(bottom, top - 1, -1): + res.append(matrix[i][left]) + left += 1 + + return res \ No newline at end of file