Ctrl K

Rooms Open from the Hall

Medium
A building has n rooms numbered from 0 to n - 1. They are linked by n - 1 two-way corridors so that there is exactly one path between any two rooms (the floor plan is a tree). Corridor corridors[i] = [a, b] joins rooms a and b. Some rooms are locked; their numbers are listed in locked. You cannot enter a locked room, not even to pass through it. Room 0 is the hall and is never locked. Return how many rooms you can visit starting from the hall (the hall itself counts).
Example 1
n=6, corridors=[[0, 1], [1, 2], [1, 3], [0, 4], [4, 5]], locked=[4] → 4

From hall 0 you reach 1, and from there 2 and 3. Room 4 is locked, so 5 is cut off. That is 4 rooms counting the hall.

Example 2
n=4, corridors=[[0, 1], [0, 2], [0, 3]], locked=[1, 2, 3] → 1

Every neighbour of the hall is locked, so only the hall itself is reachable.

Example 3
n=5, corridors=[[0, 1], [1, 2], [2, 3], [3, 4]], locked=[4] → 4
Constraints
  • 2 ≤ n ≤ 10⁵
  • len(corridors) = n - 1
  • 0 ≤ a, b < n, a ≠ b
  • The corridors form a tree
  • 1 ≤ len(locked) < n
  • 1 ≤ locked[i] < n, all numbers in locked are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsGroups Linked by Shared Tags MediumWhich Machine to Cure HardWhich Machine to Unplug HardRatio Chain Queries MediumStop a Process Branch Medium
loading Python…
Input
n=6, corridors=[[0, 1], [1, 2], [1, 3], [0, 4], [4, 5]], locked=[4]
Expected
4

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