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
27 changes: 27 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Time complexity: O(n)
# Space complexity: O(1) (excluding the output array)
#idea is to calculate the product from left to right
#and then from right to left
#eg: [1,2,3,4] : rightprod = [1,1,2,6], leftprod = [24,12,4,1]
n = len(nums)
result = [1]* n
result[0] = 1
rightprod = 1
for i in range(n):
result[i] = rightprod
rightprod *= nums[i]


# Pass 2: right product
rightprod = 1
for i in range(n - 1, -1, -1):
result[i] *= rightprod
rightprod *= nums[i]

return result
36 changes: 36 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution(object):
def findDiagonalOrder(self, mat):
"""
Time complexity O(m*n) Space complexity O(1)
:type mat: List[List[int]]
:rtype: List[int]
"""
m = len(mat)
n = len(mat[0])
result = [0 for _ in range(m*n)]
i,j = 0,0
dir = True
for idx in range(0, m*n):
result[idx] = mat[i][j]
if(dir):
if(i==0 and j!=n-1):
dir = False
j+=1
elif(j==n-1):
dir = False
i+=1
else:
i-=1
j+=1
else:
if(j==0 and i!=m-1):
dir = True
i+=1
elif(i==m-1):
dir = True
j+=1
else:
j-=1
i+=1
return result

35 changes: 35 additions & 0 deletions Problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Solution(object):
def spiralOrder(self, matrix):
"""
Time complexity O(m*n) Space complexity O(1)
:type matrix: List[List[int]]
:rtype: List[int]
"""
res = []
m = len(matrix)
n = len(matrix[0])
top = 0
bottom = m-1
left = 0
right = n-1
if not matrix or not matrix[0]:
return res

while(top<=bottom and left<=right):
for j in range(left, right+1):
res.append(matrix[top][j])
top+=1

for i in range(top, bottom+1):
res.append(matrix[i][right])
right-=1
if(top<=bottom):
for j in range(right, left-1,-1):
res.append(matrix[bottom][j])
bottom-=1
if(left<=right):
for i in range(bottom, top-1,-1):
res.append(matrix[i][left])
left+=1
return res