There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes.
Return the maximum number of nodes you can reach from node 0 without visiting a restricted node.
Note that node 0 will not be a restricted node.
Example 1:
Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5] Output: 4 Explanation: The diagram above shows the tree. We have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.
Example 2:
Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1] Output: 3 Explanation: The diagram above shows the tree. We have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.
Constraints:
2 <= n <= 105edges.length == n - 1edges[i].length == 20 <= ai, bi < nai != biedges represents a valid tree.1 <= restricted.length < n1 <= restricted[i] < nrestricted are unique.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
This problem asks for the maximum number of nodes reachable from node 0 in a tree without traversing through any restricted nodes. By modeling the tree as an undirected graph and storing restricted nodes in a hash set, we can perform a standard graph traversal. Starting from node 0, we explore accessible neighbors and count the total number of visited nodes.
Here's how the algorithm would work step-by-step:
def reachable_nodes(n, edges, restricted):
# Convert the restricted list into a set for fast lookups
restricted_set = set(restricted)
adjacency_list = [[] for _ in range(n)]
for node_u, node_v in edges:
adjacency_list[node_u].append(node_v)
adjacency_list[node_v].append(node_u)
visited_nodes = set([0])
node_queue = [0]
# Traverse the tree using breadth-first search while skipping restricted nodes
queue_head = 0
while queue_head < len(node_queue):
current_node = node_queue[queue_head]
queue_head += 1
for neighbor in adjacency_list[current_node]:
# Enqueue valid neighbors that have not been visited or restricted
if neighbor not in restricted_set and neighbor not in visited_nodes:
visited_nodes.add(neighbor)
node_queue.append(neighbor)
return len(visited_nodes)
The problem asks for the number of nodes reachable from the starting node in an undirected tree without traversing restricted nodes. We can model the tree as an adjacency list and initiate a traversal from node 0. By ignoring restricted nodes and avoiding revisited nodes, we can count all accessible nodes.
Here's how the algorithm would work step-by-step:
def reachable_nodes(n: int, edges: list[list[int]], restricted: list[int]) -> int:
# Convert restricted nodes to a set for constant-time lookup
restricted_set = set(restricted)
adjacency_list = [[] for _ in range(n)]
for node_u, node_v in edges:
adjacency_list[node_u].append(node_v)
adjacency_list[node_v].append(node_u)
# Initialize BFS traversal from the root node
queue = [0]
visited = [False] * n
visited[0] = True
reachable_count = 0
# Traverse the tree while skipping restricted and visited nodes
while queue:
current_node = queue.pop()
reachable_count += 1
for neighbor in adjacency_list[current_node]:
if not visited[neighbor] and neighbor not in restricted_set:
visited[neighbor] = True
queue.append(neighbor)
return reachable_count
| Case | How to Handle |
|---|---|
| Root node itself is in the restricted list | The algorithm checks if node zero is restricted at the start and immediately returns zero reachable nodes if true |
| Tree of size one consisting only of the root node | Since the root is not restricted, the traversal processes it and correctly returns a count of one |
| All neighbors of the root node are restricted | The traversal will not be able to visit any child nodes, resulting in a count of just one for the root itself |
| Deeply skewed tree resembling a linked list with maximum constraints | We use an iterative BFS or DFS approach with an explicit stack or queue to avoid stack overflow errors from deep recursion |
| Large graph with up to one hundred thousand nodes | Representing the tree as an adjacency list and using a visited set ensures linear time complexity of O(N) which passes within the time limit |
| Restricted nodes that do not exist in the tree | These invalid node labels are simply ignored since the traversal only encounters valid nodes present in the edge list |
| Disconnected components in the input edges despite being a valid tree | Starting traversal strictly from node zero ensures we only count nodes reachable from the root, ignoring any disconnected components |
| Duplicate edges or self-loops in the input edge list | A visited tracking set prevents infinite loops and redundant processing when the graph is traversed |