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
32 changes: 32 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#Problem 102. BINARY TREE LEVEL ORDER TRAVERSAL
# TIME COMPELXITY: O(N) where N denotes the nodes that are present in a given tree structure
# SPACE COMPLEXITY: O(N) since we will be needing to store the nodes that are coming from these level order traversal



# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
result=[]
q=deque([root])
while q:
size=len(q)
level=[]
for i in range(size):
node=q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
result.append(level)
return result


41 changes: 41 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#Problem 207. COURSE SCHEDULE
# TIME COMPELXITY: O(V+E) where V is the numberCourses and E is the prerequisites
# SPACE COMPLEXITY: O(V+E) to store the graph, queue and indegree array.

class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
indegree=[0]*numCourses
graph={}

for prerequisite in prerequisites:
indegree[prerequisite[0]]+=1
if prerequisite[1] not in graph:
graph[prerequisite[1]]=[]
graph[prerequisite[1]].append(prerequisite[0])

count=0
q=deque()

for i in range(numCourses):
if indegree[i]==0:
q.append(i)
count+=1

if not q:
return False
if count==numCourses:
return True

while q:
current=q.popleft()
dependencies=graph.get(current)
if dependencies:
for dependencie in dependencies:
indegree[dependencie]-=1
if indegree[dependencie]==0:
q.append(dependencie)
count+=1
if count==numCourses:
return True

return False