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
39 changes: 39 additions & 0 deletions diagonal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution:
def findDiagonalOrder(self, mat):
m, n = len(mat), len(mat[0])
result = [0] * (m * n)
r = c = 0
dir = True

for i in range(m * n):
result[i] = mat[r][c]

if dir:
if c == n - 1:
r += 1
dir = False
elif r == 0:
c += 1
dir = False
else:
r -= 1
c += 1
else:
if r == m - 1:
c += 1
dir = True
elif c == 0:
r += 1
dir = True
else:
r += 1
c -= 1

return result

mat = [[1,2],[3,4]]
s = Solution()
print(s.findDiagonalOrder(mat))

# TC - O(m*n)
# SC - O(1)
28 changes: 28 additions & 0 deletions prodofarrexceptself.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution:
def productExceptSelf(self, nums):
n = len(nums)
result = [0] * n

rp = 1
result[0] = 1

for i in range(1, n): # left pass
rp = rp * nums[i - 1]
result[i] = rp

#print(result)
rp = 1

for i in range(n - 2, -1, -1): # right pass
rp = rp * nums[i + 1]
# print(rp)
result[i] = result[i] * rp

return result

nums = [1,2,3,4]
s = Solution()
print(s.productExceptSelf(nums))

# TC - O(n)
# SC - O(1) auxiliary space
41 changes: 41 additions & 0 deletions spiral.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class Solution:
def spiralOrder(self, matrix):
m = len(matrix)
n = len(matrix[0])
result = []

r, c = 0, 0

for _ in range(m * n):
while c < n and matrix[r][c] != float('-inf'):
result.append(matrix[r][c])
matrix[r][c] = float('-inf')
c += 1
c -= 1; r += 1

while r < m and matrix[r][c] != float('-inf'):
result.append(matrix[r][c])
matrix[r][c] = float('-inf')
r += 1
r -= 1; c -= 1

while c >= 0 and matrix[r][c] != float('-inf'):
result.append(matrix[r][c])
matrix[r][c] = float('-inf')
c -= 1
c += 1; r -= 1

while r >= 0 and matrix[r][c] != float('-inf'):
result.append(matrix[r][c])
matrix[r][c] = float('-inf')
r -= 1
r += 1; c += 1

return result

matrix = [[1,2,3],[4,5,6],[7,8,9]]
s = Solution()
print(s.spiralOrder(matrix))

# TC = O(m*n)
# SC = O(1)