Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions diagonal_traverse.py
Original file line number Diff line number Diff line change
@@ -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<cols:
res.append(mat[i][j])
i -=1
j +=1

if j == cols:
i += 2
j -= 1
elif i < 0:
i += 1
going_up = False
else:
while i <rows 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







19 changes: 19 additions & 0 deletions product_of_array_except_self.py
Original file line number Diff line number Diff line change
@@ -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
38 changes: 38 additions & 0 deletions spiral_traversal.py
Original file line number Diff line number Diff line change
@@ -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