FastPrepMiddle Course in a Prerequisite Chain

Middle Course in a Prerequisite Chain

Intuit logoIntuit● EasyNEW GRADINTERNOA

Problem statement

Each pair [prerequisite, course] in prerequisites says that the first course must be completed immediately before the second. The pairs arrive in any order and together describe one complete, non-branching course chain.

Every course has at most one prerequisite, and no prerequisite leads to two different courses. There is exactly one starting course and one final course, and every mentioned course belongs to this one chain. The chain contains at least two courses.

Return the middle course in chain order. If the number of courses is even, return the earlier of its two middle courses. For N courses, this is the course at zero-based index (N-1)/2, rounded down.

The function receives complete course-name pairs. Preserve each name exactly, including internal spaces and case; do not split a course name into words.

Function

middleCourse(prerequisites: String[][]) → String

Examples

Example 1

prerequisites = [["DataStructures","Algorithms"],["FoundationsOfCS","OperatingSystems"],["ComputerNetworks","ComputerArchitecture"],["Algorithms","FoundationsOfCS"],["ComputerArchitecture","DataStructures"],["SoftwareDesign","ComputerNetworks"]]return = "DataStructures"

The chain is SoftwareDesign, ComputerNetworks, ComputerArchitecture, DataStructures, Algorithms, FoundationsOfCS, OperatingSystems. There are seven courses, so DataStructures at index 3 is the middle.

Example 2

prerequisites = [["OS","DB"],["algorithm","data structure"],["data structure","OS"]]return = "data structure"

The complete order is algorithm, data structure, OS, DB. There are four courses; the earlier middle is data structure at index 1, not OS.

Constraints

  • For this exercise, assume 1 <= prerequisites.length <= 999.
  • Each pair contains exactly two names, each with 1 to 50 printable ASCII characters and at least one non-space character.
  • Pairs are unique, with no self-dependencies or cycles. All pairs form exactly one directed chain containing 2 to 1000 distinct courses.

More Intuit problems

See Intuit hiring insights
Saved
public String middleCourse(String[][] prerequisites) {
    // Write your code here
}
prerequisites[["DataStructures","Algorithms"],["FoundationsOfCS","OperatingSystems"],["ComputerNetworks","ComputerArchitecture"],["Algorithms","FoundationsOfCS"],["ComputerArchitecture","DataStructures"],["SoftwareDesign","ComputerNetworks"]]
expected"DataStructures"
Checking account…