diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..a2a90693 --- /dev/null +++ b/Problem1.py @@ -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 + + \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..cf62ad92 --- /dev/null +++ b/Problem2.py @@ -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 \ No newline at end of file