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
36 changes: 36 additions & 0 deletions DiagonalMatrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Time complexity: O(n)
# Space complexity: O(1) since we are not considering the output as an extra space as it is auxiliary space.
# Did it run on leetcode: Yes

# Basically checking for out of bounds condition and updating the direction based on it and storing the result in result array

class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
m, n = len(mat), len(mat[0])
result = [0 for _ in range(m*n)]
dir = True
r,c = 0, 0
c = 0
for i in range(m*n):
result[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:
c -= 1
r += 1
return result
19 changes: 19 additions & 0 deletions ProductOfArray.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Time complexity: O(n)
# Space complexity: O(1) since we are not considering the output as an extra space as it is auxiliary space.
# Did it run on leetcode: Yes

class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1] * len(nums)
lp = 1 # left running product
for i in range(1, len(nums)):
lp = lp * nums[i - 1]
res[i] = lp

rp = 1 # right running product

for i in range(len(nums) - 2, -1, -1):
rp = rp * nums[i + 1]
res[i] *= rp

return res
33 changes: 33 additions & 0 deletions SpiralMatrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Time complexity: O(m*n)
# Space complexity: O(1) since we are not considering the output as an extra space as it is auxiliary space.
# Did it run on leetcode: Yes

# We are checking for top <= bottom and left <= right only for 2 loops because for others the for loops take care

class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
result = []
top, left = 0, 0
right = n - 1
bottom = m - 1
while (left <= right and top <= bottom):
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1

for j in range(top, bottom + 1):
result.append(matrix[j][right])
right -= 1

if (top <= bottom):
for k in range(right, left - 1, -1):
result.append(matrix[bottom][k])
bottom -= 1

if (left <= right):
for l in range(bottom, top - 1, -1):
result.append(matrix[l][left])
left += 1

return result