Reachable Nodes With Restrictions - Problem

Imagine you're exploring a connected network of locations, but some areas are off-limits! You have an undirected tree with n nodes labeled from 0 to n - 1, connected by exactly n - 1 edges.

You're given:

  • A 2D array edges where edges[i] = [a_i, b_i] represents a connection between nodes a_i and b_i
  • An array restricted containing nodes you cannot visit

Goal: Starting from node 0 (which is never restricted), find the maximum number of nodes you can reach without passing through any restricted nodes.

Think of it as exploring a city where certain intersections are blocked - you want to see how much of the city you can still explore!

Input & Output

example_1.py — Basic Tree
$ Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]
Output: 4
💡 Note: Starting from node 0, we can reach nodes 1, 2, and 3. We cannot reach nodes 4, 5, or 6 because nodes 4 and 5 are restricted, blocking the path to node 6.
example_2.py — Single Restriction
$ Input: n = 4, edges = [[0,1],[1,2],[2,3]], restricted = [2]
Output: 2
💡 Note: From node 0, we can only reach node 1. Node 2 is restricted, which also blocks access to node 3.
example_3.py — No Restrictions
$ Input: n = 5, edges = [[0,1],[0,2],[1,3],[1,4]], restricted = []
Output: 5
💡 Note: With no restrictions, we can reach all nodes from node 0. The tree is fully traversable.

Constraints

  • 2 ≤ n ≤ 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • edges represents a valid tree
  • 1 ≤ restricted.length < n
  • 0 ≤ restricted[i] < n
  • All the values of restricted are unique
  • restricted does not contain 0

Visualization

Tap to expand
Reachable Nodes With Restrictions INPUT Tree Structure (n=7) 0 1 2 3 4 5 6 Reachable Restricted Blocked n = 7 edges = [[0,1],[1,2],[3,1], [4,0],[0,5],[5,6]] restricted = [4, 5] ALGORITHM STEPS 1 Build Adjacency List Create graph from edges 2 Mark Restricted Set Hash set for O(1) lookup 3 DFS from Node 0 Skip restricted nodes 4 Count Visited Return reachable count DFS Traversal Order 0 1 2 3 Nodes 4,5,6 blocked FINAL RESULT Reachable Nodes 0 1 2 3 Output 4 OK - 4 nodes reached (0, 1, 2, 3) Key Insight: DFS explores all reachable nodes from start. By marking restricted nodes as "visited" before DFS, we prevent traversal through them, effectively blocking paths to unreachable sections of the tree. TutorialsPoint - Reachable Nodes With Restrictions | DFS Approach
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
42.7K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen