From 7e85580d25c29de58ab562b35af7c5a9c456ae44 Mon Sep 17 00:00:00 2001 From: Srijha-Kalyan <87617310+Srijha-Kalyan@users.noreply.github.com> Date: Mon, 17 Nov 2025 19:35:19 -0500 Subject: [PATCH] Add files via upload --- Problem1.py | 27 +++++++++++++++++++++++++++ Problem2.py | 36 ++++++++++++++++++++++++++++++++++++ Problem3.py | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 Problem1.py create mode 100644 Problem2.py create mode 100644 Problem3.py diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..d6a5f15a --- /dev/null +++ b/Problem1.py @@ -0,0 +1,27 @@ +class Solution(object): + def productExceptSelf(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + # Time complexity: O(n) + # Space complexity: O(1) (excluding the output array) + #idea is to calculate the product from left to right + #and then from right to left + #eg: [1,2,3,4] : rightprod = [1,1,2,6], leftprod = [24,12,4,1] + n = len(nums) + result = [1]* n + result[0] = 1 + rightprod = 1 + for i in range(n): + result[i] = rightprod + rightprod *= nums[i] + + + # Pass 2: right product + rightprod = 1 + for i in range(n - 1, -1, -1): + result[i] *= rightprod + rightprod *= nums[i] + + return result \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..d0198a4a --- /dev/null +++ b/Problem2.py @@ -0,0 +1,36 @@ +class Solution(object): + def findDiagonalOrder(self, mat): + """ + Time complexity O(m*n) Space complexity O(1) + :type mat: List[List[int]] + :rtype: List[int] + """ + m = len(mat) + n = len(mat[0]) + result = [0 for _ in range(m*n)] + i,j = 0,0 + dir = True + for idx in range(0, m*n): + result[idx] = mat[i][j] + if(dir): + if(i==0 and j!=n-1): + dir = False + j+=1 + elif(j==n-1): + dir = False + i+=1 + else: + i-=1 + j+=1 + else: + if(j==0 and i!=m-1): + dir = True + i+=1 + elif(i==m-1): + dir = True + j+=1 + else: + j-=1 + i+=1 + return result + \ No newline at end of file diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..557e37e5 --- /dev/null +++ b/Problem3.py @@ -0,0 +1,35 @@ +class Solution(object): + def spiralOrder(self, matrix): + """ + Time complexity O(m*n) Space complexity O(1) + :type matrix: List[List[int]] + :rtype: List[int] + """ + res = [] + m = len(matrix) + n = len(matrix[0]) + top = 0 + bottom = m-1 + left = 0 + right = n-1 + if not matrix or not matrix[0]: + return res + + while(top<=bottom and left<=right): + for j in range(left, right+1): + res.append(matrix[top][j]) + top+=1 + + for i in range(top, bottom+1): + res.append(matrix[i][right]) + right-=1 + if(top<=bottom): + for j in range(right, left-1,-1): + res.append(matrix[bottom][j]) + bottom-=1 + if(left<=right): + for i in range(bottom, top-1,-1): + res.append(matrix[i][left]) + left+=1 + return res + \ No newline at end of file