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
City Road Network ExplorationDEPOTNode 01243BLOCKED5โœ“ Exploreโœ“ Exploreโœ“ Exploreโœ— BLOCKEDHash Set Lookuprestricted = {3}Check node 3: O(1)Result: โœ— Blocked!Final CountReachable: 0,1,2,4Blocked: 3Answer: 4 nodes
Understanding the Visualization
1
Mark Blocked Areas
Convert restricted nodes array to hash set for instant lookup
2
Start Exploration
Begin DFS from node 0 (the depot/starting point)
3
Check Before Moving
For each neighbor, check if it's blocked using O(1) hash lookup
4
Count Reachable
Accumulate count of all nodes visited during the traversal
Key Takeaway
๐ŸŽฏ Key Insight: Use DFS with hash set for O(1) restriction checks - single traversal gives O(n) optimal solution!
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