Skip to content

Commit b848fef

Browse files
committed
Add 210. Course Schedule II
1 parent fc5eb4e commit b848fef

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package sierikov.leetcode.tasks.medium
2+
3+
import scala.annotation.tailrec
4+
import scala.collection.immutable.Queue
5+
6+
// Leetcode: https://leetcode.com/problems/course-schedule-ii/description/
7+
object CourseSheduleII {
8+
def findOrder(numCourses: Int, prerequisites: Array[Array[Int]]): Array[Int] = {
9+
val map: Map[Int, Array[Int]] = createMap(prerequisites)
10+
val starting = Queue.apply(findStarting(numCourses, createMap(prerequisites)).toArray*)
11+
iterateOverCourses(map, starting)
12+
}
13+
14+
def createMap(prerequisites: Array[Array[Int]]): Map[Int, Array[Int]] =
15+
prerequisites.groupMap(_.apply(0))(_.tail.head)
16+
17+
def findStarting(n: Int, map: Map[Int, Array[Int]]): Set[Int] =
18+
(0 until n).filter(i => map.get(i).isEmpty).toSet
19+
20+
@scala.annotation.tailrec
21+
def iterateOverCourses(
22+
map: Map[Int, Array[Int]],
23+
startingCourses: Queue[Int],
24+
takenCourses: Vector[Int] = Vector.empty
25+
): Array[Int] = startingCourses.dequeueOption match
26+
case Some((course, queue)) => {
27+
val removedVertex = map.view.mapValues(_.filter(_ != course)).toMap
28+
val (coursesWithNoDependencies, otherCourses) = removedVertex.partition(_._2.isEmpty)
29+
iterateOverCourses(
30+
otherCourses,
31+
queue.enqueueAll(coursesWithNoDependencies.keySet),
32+
takenCourses :+ course
33+
)
34+
}
35+
case None if map.isEmpty => takenCourses.toArray
36+
case None => Array.emptyIntArray
37+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package sierikov.leetcode.tasks.medium
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should.Matchers
5+
6+
class CourseSheduleIITest extends AnyFlatSpec with Matchers {
7+
import CourseSheduleII._
8+
9+
it should "pass example test" in {
10+
val result = findOrder(
11+
4,
12+
Array(Array(1, 0), Array(2, 0), Array(3, 1), Array(3, 2))
13+
)
14+
15+
result should (equal(Array(0, 2, 1, 3)) or equal(Array(0, 1, 2, 3)))
16+
}
17+
18+
it should "detect cycles in the graph" in {
19+
val result = findOrder(
20+
4,
21+
Array(Array(1, 0), Array(2, 0), Array(3, 1), Array(0, 3))
22+
)
23+
24+
result shouldBe Array.emptyIntArray
25+
}
26+
}

0 commit comments

Comments
 (0)