Taro Logo

Reachable Nodes With Restrictions

Medium
Asked by:
Profile picture
0 views
Topics:
TreesGraphs

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 <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • edges represents a valid tree.
  • 1 <= restricted.length < n
  • 1 <= restricted[i] < n
  • All the values of restricted are unique.

Solution


Clarifying Questions

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:

  1. What is the maximum number of nodes in the tree (the value range for $n$), and can the restricted list be empty?
  2. Are the node labels guaranteed to be from $0$ to $n-1$, and is the starting node $0$ always guaranteed to be unrestricted?
  3. Can any of the restricted nodes appear as part of the edge list, and how should we handle a scenario where the root node itself is restricted?
  4. Is the input graph guaranteed to be a valid, connected tree with no cycles, or could there be disconnected components or multiple edges?
  5. Should the return value be a standard integer representing the count of unique reachable nodes, and what should be returned if no nodes can be reached beyond the root?

Brute Force Solution

Approach

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:

  1. Convert the list of restricted nodes into a hash set to enable constant-time membership checks.
  2. Build an adjacency list representation of the tree from the given edge list.
  3. Initialize a queue and a visited set starting with node 0 to manage the traversal.
  4. Iteratively dequeue each node and inspect all of its adjacent neighbors.
  5. Add unvisited and non-restricted neighbors to both the queue and the visited set.
  6. Return the total count of visited nodes once the queue is fully processed.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n) – Building the adjacency list takes O(n) time because there are n - 1 edges. The breadth-first search explores each valid node and edge at most once, with restricted node checks taking O(1) time.
Space Complexity
O(n) – The adjacency list, restricted set, visited set, and queue all store at most O(n) elements.

Optimal Solution

Approach

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:

  1. Store restricted nodes in a hash set to allow O(1) membership checks.
  2. Construct an undirected adjacency list from the given edges.
  3. Set up a queue or stack for traversal starting at node 0 and initialize a visited array.
  4. Process each reachable node sequentially, incrementing the count of reached nodes.
  5. For each unvisited neighbor not present in the restricted set, mark it as visited and add it to the traversal queue.
  6. Return the final count of reachable nodes after the traversal completes.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – Building the adjacency list takes O(n) time since there are n - 1 edges. The breadth-first or depth-first search visits each reachable node and edge at most once, and checking the restricted set takes O(1) time per neighbor.
Space Complexity
O(n) – The adjacency list requires O(n) space to store the tree edges. Additionally, the restricted set, visited array, and traversal queue each require up to O(n) space.

Edge Cases

Root node itself is in the restricted list
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
A visited tracking set prevents infinite loops and redundant processing when the graph is traversed