From 0b40342d184cc2fd65265f21d5abe0c76ddd98f4 Mon Sep 17 00:00:00 2001 From: allurkarsneha Date: Thu, 13 Aug 2026 18:37:26 -0500 Subject: [PATCH] Completed Leetcode 54, 498 and 238 --- Problem3-Leetcode54.py | 36 ++++++++++++++++++++++++++++++++++++ problem1-leetcode238.py | 24 ++++++++++++++++++++++++ problem2-Leetcode498.py | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 Problem3-Leetcode54.py create mode 100644 problem1-leetcode238.py create mode 100644 problem2-Leetcode498.py diff --git a/Problem3-Leetcode54.py b/Problem3-Leetcode54.py new file mode 100644 index 00000000..aec60ff3 --- /dev/null +++ b/Problem3-Leetcode54.py @@ -0,0 +1,36 @@ +#Time Complexity: O(m*n) +#Space Complexity: O(1) + +class Solution(object): + def spiralOrder(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + result = [] + if not matrix: + return result + + top, bottom = 0, len(matrix) - 1 + left, right = 0, len(matrix[0]) - 1 + + 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 \ No newline at end of file diff --git a/problem1-leetcode238.py b/problem1-leetcode238.py new file mode 100644 index 00000000..93f61e6f --- /dev/null +++ b/problem1-leetcode238.py @@ -0,0 +1,24 @@ +#Time Complexity: O(n) +#Space Complexity: O(n) + +class Solution(object): + def productExceptSelf(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + n, runningProduct = len(nums), 1 + leftProduct = [0] * n + leftProduct[0] = 1 + + for i in range(1, len(nums)): + runningProduct = runningProduct * nums[i - 1] + leftProduct[i] = runningProduct + + runningProduct = 1 + for i in range(n-2, -1, -1): + runningProduct = runningProduct * nums[i + 1] + leftProduct[i] = leftProduct[i] * runningProduct + + return leftProduct + \ No newline at end of file diff --git a/problem2-Leetcode498.py b/problem2-Leetcode498.py new file mode 100644 index 00000000..3cf144b6 --- /dev/null +++ b/problem2-Leetcode498.py @@ -0,0 +1,37 @@ +#Time Complexity: O(m*n) +#Space Complexity: O(1) + +class Solution(object): + def findDiagonalOrder(self, mat): + """ + :type mat: List[List[int]] + :rtype: List[int] + """ + m, n = len(mat), len(mat[0]) + r, c, x, flag = 0, 0, m * n, True + arr = [] + for _ in range(x): + arr.append(mat[r][c]) + if flag: + if r == 0 and c != n - 1: + c += 1 + flag = False + elif c == n - 1: + r += 1 + flag = False + else: + r -= 1 + c += 1 + else: + if c == 0 and r != m - 1: + r += 1 + flag = True + elif r == m - 1: + c += 1 + flag = True + else: + r += 1 + c -= 1 + + return arr + \ No newline at end of file