Ctrl K

Stop a Process Branch

Medium
A system runs n processes that form a tree: every process except a single root has a parent, the process that launched it. ids[i] is the id of the i-th process and parents[i] is the id of its parent; for the root, parents[i] = 0. When a process is stopped, all of its children stop with it, and their children too, and so on. Return the ids of every process that stops when you stop process target. The order does not matter.
Example 1
ids=[4, 8, 2, 6, 9], parents=[0, 4, 4, 8, 8], target=8 → [8, 6, 9]

Process 8 started 6 and 9, so 8, 6 and 9 stop. Processes 4 and 2 keep running.

Example 2
ids=[3, 1, 5], parents=[5, 3, 0], target=5 → [5, 3, 1]

5 is the root of the whole tree, so everything stops.

Example 3
ids=[7], parents=[0], target=7 → [7]
Constraints
  • 1 ≤ n = len(ids) = len(parents) ≤ 5·10⁴
  • 1 ≤ ids[i] ≤ 5·10⁴, all ids are distinct
  • 0 ≤ parents[i] ≤ 5·10⁴
  • Exactly one process has parents[i] = 0, and the links form a tree
  • target is one of the ids
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSmallest Shared Territory MediumRooms Open from the Hall MediumTree Columns, Top Down MediumPath Totals in a Coded Tree MediumMerge Contact Cards Medium
loading Python…
Input
ids=[4, 8, 2, 6, 9], parents=[0, 4, 4, 8, 8], target=8
Expected
[8, 6, 9]

Run checks the first 3 tests in your browser. Submit checks all 64 tests on the server, hidden ones included.