diff --git a/Problem_1.py b/Problem_1.py new file mode 100644 index 00000000..01ba5ecc --- /dev/null +++ b/Problem_1.py @@ -0,0 +1,21 @@ +#Time Complexity : O(n) +#Space Complexity : O(1) +#Did this code successfully run on Leetcode :Yes +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + result = [1]*len(nums) + prefix = 1 + + for i in range(n): + result[i] *= prefix + prefix *= nums[i] + + suffix = 1 + for i in range(n-1,-1,-1): + result[i] *= suffix + suffix *= nums[i] + + return result + + diff --git a/Problem_2.py b/Problem_2.py new file mode 100644 index 00000000..313d73ac --- /dev/null +++ b/Problem_2.py @@ -0,0 +1,35 @@ +#Time Complexity : O(m*n) where m is number of rows and n is number of columns +#Space Complexity : O(1) +#Did this code successfully run on Leetcode :Yes +class Solution: + def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]: + m, n = len(mat), len(mat[0]) + result = [0] * (m * n) + r = c = 0 + dir = True + + for i in range(m * n): + result[i] = mat[r][c] + + if dir: + if c == n - 1: + r += 1 + dir = False + elif r == 0: + c += 1 + dir = False + else: + r -= 1 + c += 1 + else: + if r == m - 1: + c += 1 + dir = True + elif c == 0: + r += 1 + dir = True + else: + r += 1 + c -= 1 + + return result diff --git a/Problem_3.py b/Problem_3.py new file mode 100644 index 00000000..1c166f83 --- /dev/null +++ b/Problem_3.py @@ -0,0 +1,34 @@ +#Time Complexity : O(m*n) +#Space Complexity : O(1) +#Did this code successfully run on Leetcode :Yes + +class Solution: + def spiralOrder(self, matrix): + m = len(matrix) + n = len(matrix[0]) + + top, bottom, left, right = 0, m - 1, 0, n - 1 + + result = [] + + while top <= bottom and left <= right: + + for i in range(left, right + 1): + result.append(matrix[top][i]) + top += 1 + + for i in range(top, bottom + 1): + result.append(matrix[i][right]) + right -= 1 + + if top <= bottom: + for i in range(right, left - 1, -1): + result.append(matrix[bottom][i]) + bottom -= 1 + + if left <= right: + for i in range(bottom, top - 1, -1): + result.append(matrix[i][left]) + left += 1 + + return result