diff --git a/diagonal-traverse.py b/diagonal-traverse.py new file mode 100644 index 00000000..96249585 --- /dev/null +++ b/diagonal-traverse.py @@ -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 + diff --git a/product-array-self.py b/product-array-self.py new file mode 100644 index 00000000..11b14a9c --- /dev/null +++ b/product-array-self.py @@ -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 \ No newline at end of file diff --git a/spiral-matrix.py b/spiral-matrix.py new file mode 100644 index 00000000..d0d9b8ae --- /dev/null +++ b/spiral-matrix.py @@ -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 \ No newline at end of file