Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -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
38 changes: 38 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -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
37 changes: 37 additions & 0 deletions Problem3.py
Original file line number Diff line number Diff line change
@@ -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