diff --git a/Problem_1.py b/Problem_1.py new file mode 100644 index 00000000..d9faa96b --- /dev/null +++ b/Problem_1.py @@ -0,0 +1,18 @@ +# https://leetcode.com/problems/product-of-array-except-self/description/ + +class Solution: + def productExceptSelf(self, nums): + n = len(nums) + result = [1] + for i in range(n - 1): + result.append(nums[i] * result[i]) + right = 1 + for i in range(n - 1, -1, -1): + result[i] = result[i] * right + right = nums[i] * right + return result + + +nums = [-1,1,0,-3,3] +sl = Solution() +print(sl.productExceptSelf(nums)) \ No newline at end of file diff --git a/Problem_2.py b/Problem_2.py new file mode 100644 index 00000000..8ca9c71f --- /dev/null +++ b/Problem_2.py @@ -0,0 +1,30 @@ +class Solution: + def findDiagonalOrder(self, mat): + result = [] + rows, cols = len(mat), len(mat[0]) + total_elements = rows * cols + flag = True # True means up, False means down + cr, cc = 0, 0 + while len(result) < total_elements: + result.append(mat[cr][cc]) + if flag: + if cc == cols - 1: + cr += 1 + flag = False + elif cr == 0: + cc += 1 + flag = False + else: + cr -= 1 + cc += 1 + else: + if cr == rows - 1: + cc += 1 + flag = True + elif cc == 0: + cr += 1 + flag = True + else: + cc -= 1 + cr += 1 + return result diff --git a/Problem_3.py b/Problem_3.py new file mode 100644 index 00000000..48d77fe4 --- /dev/null +++ b/Problem_3.py @@ -0,0 +1,36 @@ +# https://leetcode.com/problems/spiral-matrix/description/ + +class Solution: + def spiralOrder(self, matrix): + rows, cols = len(matrix), len(matrix[0]) + top = 0 + right = cols - 1 + bottom = rows - 1 + left = 0 + result = [] + while top <= bottom and left <= right: + + for i in range(left, right + 1, 1): + result.append(matrix[top][i]) + top += 1 + + for i in range(top, bottom + 1, 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 + +matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] + +sl = Solution() +print(sl.spiralOrder(matrix)) \ No newline at end of file