Middle Course in One Prerequisite Chain
Problem statement
Each row of pairs is [prerequisite,nextCourse]. Return the middle course in the prerequisite sequence.
The relationships form one linear chain with no branching and no separate chains. For this exercise, assume the relationships are acyclic, duplicate pairs have no effect, and only endpoints appearing in pairs are represented.
For this exercise, assume the middle is the course at zero-based position floor((numberOfCourses-1)/2) from the first course. For even-length chains, choose the earlier of the two middle courses.
For this exercise, assume empty pairs encode no course and return an empty string. A standalone single course is not representable by this interface; every nonempty valid input has at least two courses.
Function
middleCourse(pairs: String[][]) → StringExamples
Example 1
pairs = [["M1","M2"],["M2","M3"],["M3","M4"]]return = "M2"This authored four-course chain returns the earlier of its two middle courses: M2.
Example 2
pairs = [["C","D"],["A","B"],["D","E"],["B","C"]]return = "C"This authored five-course chain is A,B,C,D,E despite shuffled pairs, so its middle is C.
Constraints
- For this exercise, assume
0 <= pairs.length <= 250, with exactly two strings per row. - After duplicates are ignored, nonempty input forms exactly one directed acyclic linear chain; no branching, multiple chains or isolated course list.
- For this exercise, assume course names are distinct case-sensitive printable ASCII strings of length
1through10.