Produce valid student lineup from parent array
Company: Intuit
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates understanding of rooted tree hierarchies, parent-before-child ordering constraints, and lexicographic minimality when constructing a valid sequence, testing competencies in tree/graph algorithms and deterministic ordering logic.
Constraints
- 1 <= n <= 200000
- Students are labeled 1 through n
- Exactly one entry in par is -1
- For every other student, par[i] is in the range [1, n]
- The input forms a valid rooted tree
Examples
Input: ([-1, 1, 1, 2, 2, 2, 2],)
Expected Output: [1, 2, 3, 4, 5, 6, 7]
Explanation: Student 1 must come first. Then students 2 and 3 become available, so choose 2 before 3. After choosing 2, students 4, 5, 6, 7 become available, but 3 is still smaller than all of them, so it comes next.
Input: ([-1],)
Expected Output: [1]
Explanation: There is only one student, so the lineup contains just that student.
Input: ([-1, 1, 1, 2],)
Expected Output: [1, 2, 3, 4]
Explanation: After placing 1, students 2 and 3 are available. Pick 2 first. Then both 3 and 4 are available, and 3 is smaller, so it must come before 4.
Input: ([2, -1, 2, 1],)
Expected Output: [2, 1, 3, 4]
Explanation: Student 2 is the root. After placing 2, students 1 and 3 are available. Pick 1 first, then 3, then 4.
Input: ([4, 4, 4, -1, 2, 2, 1],)
Expected Output: [4, 1, 2, 3, 5, 6, 7]
Explanation: Student 4 is the root. After 4, students 1, 2, 3 are available. Choose 1, then 2, then 3. After 2, students 5 and 6 become available, and after 1, student 7 becomes available. The smallest eligible student is always chosen next.
Hints
- Think of this as finding the lexicographically smallest topological ordering of a tree.
- At any step, all students whose parent is already in the lineup are eligible. Use a min-heap to always choose the smallest eligible student.