diff --git a/CourseSchedule.kt b/CourseSchedule.kt new file mode 100644 index 00000000..9ca0f5c4 --- /dev/null +++ b/CourseSchedule.kt @@ -0,0 +1,38 @@ +// In this problem, we need to determine if we can complete all courses with given prerequisites. We create adjacency list to represent the graph and an indegree array to track the number of +// prerequisites for each course. We use a queue to perform a topological sort. We start by adding all courses that have zero indegree to the queue. +//Then we process each course in the queue by reducing the indregree of its dependent courses. If any dependent course's indegree becomes zero, we add it to the queue. +// Time complexity is O(V + E) where V is no. of courses and E is no. of prerequisites. Space complexity is O(V + E) for adjacency list and indegree array. + +class Solution { + fun canFinish(numCourses: Int, prerequisites: Array): Boolean { + val adj = Array(numCourses){mutableListOf()} + val indegree = IntArray(numCourses) + + for(p in prerequisites) { + val c = p[0] + val pre = p[1] + adj[pre].add(c) + indegree[c]++ + } + + val q : ArrayDeque = ArrayDeque() + for(i in 0 until numCourses) { + if(indegree[i] == 0) { + q.addLast(i) + } + } + + var seen = 0 + while(q.isNotEmpty()) { + val u = q.removeFirst() + seen++ + + for(v in adj[u]) { + if(--indegree[v] == 0) { + q.addLast(v) + } + } + } + return seen == numCourses + } +} \ No newline at end of file diff --git a/LevelOrderTraversal.kt b/LevelOrderTraversal.kt new file mode 100644 index 00000000..47e551e2 --- /dev/null +++ b/LevelOrderTraversal.kt @@ -0,0 +1,40 @@ +//In this problem, we need to perform a level order traversal of a binary tree. This means we visit all the nodes at each level of the tree from left to right. +// We maintain a queue to keep track of the nodes at the current levele. We start by adding the root node to the queue. Then we enter a loop that continues until the queue is empty. +// In each iteration of the loop, we get the no. of nodes in the queue and add them to a level list. For each node we also add its left and right childeren to the queue. +// Time complexity is O(n) where n is the no. of nodes. Space complexity is O(w) where w is the max no. of nodes at any level. + +/** + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun levelOrder(root: TreeNode?): List> { + if (root == null) return emptyList() + + val result = mutableListOf>() + val q : ArrayDeque = ArrayDeque() + q.addLast(root) + + while(q.isNotEmpty()) { + val size = q.size + val level = mutableListOf() + + for(i in 0 until size) { + val node = q.removeFirst() + level.add(node.`val`) + node.left?.let {q.addLast(it)} + node.right?.let {q.addLast(it)} + } + + result.add(level) + } + + return result + } +} \ No newline at end of file