diff --git a/courseScheduler.py b/courseScheduler.py new file mode 100644 index 00000000..3f51de18 --- /dev/null +++ b/courseScheduler.py @@ -0,0 +1,31 @@ +# Time Complexity : O(V + E) +# Space Complexity : O(V + E) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Build a graph using adjacency list and track indegree of each course. +# Use BFS to process courses with indegree 0 and check if all courses can be completed + + + +class Solution: + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: + graph = [[] for _ in range(numCourses)] + indegree = [0] * numCourses + + for course, prereq in prerequisites: + graph[prereq].append(course) + indegree[course] += 1 + + q = deque([c for c in range(numCourses) if indegree[c] == 0]) + taken = 0 + + while q: + cur = q.popleft() + taken += 1 + + for nxt in graph[cur]: + indegree[nxt] -= 1 + if indegree[nxt] == 0: + q.append(nxt) + + return taken == numCourses \ No newline at end of file diff --git a/levelOrder.py b/levelOrder.py new file mode 100644 index 00000000..61c07c88 --- /dev/null +++ b/levelOrder.py @@ -0,0 +1,34 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Use a queue to perform BFS traversal of the tree level by level. +# For each level, process all nodes currently in the queue, collect their values, and push their children for the next level. + +# 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]]: + q = deque() + res = [] + q.append(root) + + while len(q): + dup_list = [] + for i in range(len(q)): + node = q.popleft() + if node is not None: + dup_list.append(node.val) + if node is not None: + q.append(node.left) + if node is not None: + q.append(node.right) + if dup_list: + res.append(dup_list) + return res + + \ No newline at end of file