Skip to content
Open

a1 #1974

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
42 changes: 42 additions & 0 deletions diagonal-traverse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@

# O(m*n) time, O(m*n) space

# start with a flat array of length of m*n, iterate through that array, moving right and left pointers depending on boundaries
# top left, bottom right, column is 0, row is 0. Flag is True means going up, Flag false means going down

class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
m = len(mat)
n = len(mat[0])

res = [0]*(n*m)

flag = True # True going up, False going down

r=0
c=0
for i in range(len(res)):
res[i] = mat[r][c]
if flag:
if c == n-1:
r+=1
flag = False
elif r == 0:
c+=1
flag = False
else:
r-=1
c+=1
else:
if r == m-1:
c+=1
flag=True
elif c == 0:
r+=1
flag=True
else:
r+=1
c-=1

return res

21 changes: 21 additions & 0 deletions product-array-self.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

# time O(n), space O(n)

# iterate through res to first generate prefixes, then take prefixes and multiply by suffix in opposite order
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:

# nums = [1,2,3,4]
res = [1]*len(nums)

prefix = 1
for i in range(len(nums)):
res[i]*=prefix
prefix*=nums[i]

suffix = 1
for i in range(len(nums)-1,-1,-1):
res[i]*=suffix
suffix*=nums[i]

return res
36 changes: 36 additions & 0 deletions spiral-matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

# time O(n*m), space O(n*m)
# track top, left, right, bottom pointers and iterate through the spiral of the matrix, adding each matrix value to result
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []

n = len(matrix) # rows
m = len(matrix[0]) # cols

left = 0
right = m - 1
top = 0
bottom = n - 1

while left <= right and top <= bottom:
for c in range(left, right+1):
result.append(matrix[top][c])
top+=1
for r in range(top,bottom+1):
result.append(matrix[r][right])
right-=1

if not (left <= right and top <= bottom):
break

for c in range(right, left-1,-1):
result.append(matrix[bottom][c])
bottom -= 1
for r in range(bottom, top-1, -1):
result.append(matrix[r][left])
left+=1



return result