diff --git a/SpiralMatrix.py b/SpiralMatrix.py new file mode 100644 index 00000000..cd83c366 --- /dev/null +++ b/SpiralMatrix.py @@ -0,0 +1,40 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + if not matrix: + return [] + + m = len(matrix) + n = len(matrix[0]) + arr = [0] * (m * n) + j = 0 + # right. down. left. up. + directions = [[0,1],[1,0],[0,-1],[-1,0]] + dr = 0 + visit = set() + r = c = 0 + + while j != len(arr): + arr[j] = matrix[r][c] + visit.add((r,c)) + j += 1 + + di, dj = directions[dr] + ni, nj = r + di, c + dj + + if 0 <= ni < m and 0 <= nj < n and (ni,nj) not in visit: + r,c = ni,nj + else: + dr = (dr + 1) % 4 + di,dj = directions[dr] + r += di + c += dj + + return arr + + + + + + + + diff --git a/diagonalTraverse.py b/diagonalTraverse.py new file mode 100644 index 00000000..ac8e404f --- /dev/null +++ b/diagonalTraverse.py @@ -0,0 +1,36 @@ +class Solution: + def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]: + dir = True + r = c = 0 + m,n = len(mat), len(mat[0]) + result = [0] * (m * n) + + for i in range(m*n): + result[i] = mat[r][c] + + if dir: + if c == n - 1: + dir = False + r += 1 + + elif r == 0: + dir = False + c += 1 + + else: + r -= 1 + c += 1 + else: + if r == m-1: + dir = True + c += 1 + + elif c == 0: + dir = True + r += 1 + else: + r += 1 + c -= 1 + return result + + diff --git a/productarray.py b/productarray.py new file mode 100644 index 00000000..f28435ef --- /dev/null +++ b/productarray.py @@ -0,0 +1,14 @@ +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + space = [1] * len(nums) + + left = 1 + for i in range(len(nums)): + space[i] = left + left *= nums[i] + + right = 1 + for j in range(len(nums)-1,-1,-1): + space[j] *= right + right *= nums[j] + return space \ No newline at end of file