From d9e3163d9c4eb95c234b4fb464dc5836a5d9e9dc Mon Sep 17 00:00:00 2001 From: Megha Raykar Date: Tue, 7 Jul 2026 16:58:58 -0700 Subject: [PATCH] Array-1 all problems added --- Problem1.py | 21 +++++++++++++++++++++ Problem2.py | 38 ++++++++++++++++++++++++++++++++++++++ Problem3.py | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 96 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..206a5769 --- /dev/null +++ b/Problem1.py @@ -0,0 +1,21 @@ +# https://leetcode.com/problems/product-of-array-except-self/ +# TC: O(3n) => O(n) +# SC: O(n) + +# This solution uses running sum logic. Iterate through input array nums from left to right to calculate product of elements except that +# element in res array. Second iteration will be iterating the nums array in reverse direction to calculate product of elements except +# that element, multiply the value of res[i] + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + res = [1] * len(nums) + + for i in range(1, len(nums)): + res[i] = res[i-1] * nums[i-1] + + prod = 1 + for i in range(len(nums) - 2, -1, -1): + prod = prod * nums[i+1] + res[i] = prod * res[i] + + return res \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..05858ecb --- /dev/null +++ b/Problem2.py @@ -0,0 +1,38 @@ +# https://leetcode.com/problems/diagonal-traverse/description/ + +class Solution: + def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]: + + m = len(mat) + n = len(mat[0]) + + re = [0] * m*n + + r, c = 0, 0 + dir = True + + for i in range(m*n): + re[i] = mat[r][c] + + if dir: + if r == 0 and c != n-1: + c += 1 + dir = False + elif c == n-1: + r += 1 + dir = False + else: + r -= 1 + c += 1 + else: + if c == 0 and r != m-1: + r += 1 + dir = True + elif r == m-1: + c += 1 + dir = True + else: + r += 1 + c -= 1 + + return re \ No newline at end of file diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..ab101bd6 --- /dev/null +++ b/Problem3.py @@ -0,0 +1,37 @@ +# https://leetcode.com/problems/spiral-matrix/description/ + +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + + m = len(matrix) + n = len(matrix[0]) + + top = 0 + bottom = m - 1 + left = 0 + right = n - 1 + + re = [] + + while top <= bottom and left <= right: + + for i in range(left, right+1): + re.append(matrix[top][i]) + top += 1 + + if top <= bottom and left <= right: + for i in range(top, bottom+1): + re.append(matrix[i][right]) + right -= 1 + + if top <= bottom and left <= right: + for i in range(right, left-1, -1): + re.append(matrix[bottom][i]) + bottom -= 1 + + if top <= bottom and left <= right: + for i in range(bottom, top-1, -1): + re.append(matrix[i][left]) + left += 1 + + return re \ No newline at end of file