Taro Logo

Count Non Adjacent Subsets in a Rooted Tree

#15 Most AskedHard
0 views
Topics:
TreesDynamic ProgrammingRecursion

You are given a rooted tree with n nodes labeled from 0 to n - 1, represented by an integer array parent of length n, where:

  • parent[0] = -1 (node 0 is the root).
  • For each 1 <= i < n, parent[i] is the parent of node i (0 <= parent[i] < i).

You are also given an integer array nums of length n, where nums[i] is the value of node i, and an integer k.

A non-empty subset of nodes is called valid if:

  • The sum of the values of the selected nodes is divisible by k.
  • No two selected nodes are adjacent in the tree (no node and its direct parent are both included in the subset).

Return the number of valid subsets modulo 109 + 7.

Example 1:

Input: parent = [-1,0,1], nums = [1,2,3], k = 3

Output: 1

Explanation:

​​​​​​​

The only valid subset is {2}. It contains node 2 with value 3, which is divisible by 3.

Example 2:

Input: parent = [-1,0,0,0], nums = [2,1,2,1], k = 3

Output: 2

Explanation:

​​​​​​​​​​​​​​

The valid subsets are:

  • {1, 2}: Nodes 1 and 2 are both children of node 0 and not directly connected to each other. Their values sum to 1 + 2 = 3, which is divisible by 3.
  • {2, 3}: Nodes 2 and 3 are also non-adjacent. Their values sum to 2 + 1 = 3, which is divisible by 3.

No other subset satisfies both conditions. Therefore, the answer is 2.

Constraints:

  • n == parent.length == nums.length
  • 1 <= n <= 1000
  • parent[0] == -1
  • For all 1 <= i < n:
    • 0 <= parent[i] < i
  • 1 <= nums[i] <= 109
  • 1 <= k <= 100​​​​​​​​​​​​​​​​​​​​​
  • parent describes a valid rooted tree.

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, and should the final answer be returned modulo a specific number (such as $10^9 + 7$) to prevent integer overflow?
  2. How is the tree represented in the input? Is it given as a root node object with a list of children, or as an adjacency list/edge list?
  3. Does the node's integer value matter for the definition of a valid subset, or are we simply counting subsets of nodes where no two chosen nodes share an edge regardless of their stored values?
  4. Is the empty set considered a valid non-adjacent subset, meaning the minimum possible count is always at least 1?
  5. Can the tree be degenerate (e.g., a skewed tree resembling a linked list), and what is the maximum depth we should expect to prevent stack overflow from recursion?

Brute Force Solution

Approach

This problem asks for the number of valid non-adjacent subsets in a rooted tree whose values sum to a multiple of k. Because every node's parent has an index smaller than the node itself, the tree can be processed in reverse topological order from node n - 1 down to 1. For each node, we maintain two remainder distributions modulo k: one where the node is excluded and one where it is included.

Here's how the algorithm would work step-by-step:

  1. Initialize dynamic programming states for each node to track subset counts for each remainder modulo k when the node is chosen or not chosen.
  2. Base the initial state on an empty subset for the excluded case and the node's own value modulo k for the included case.
  3. Iterate through all nodes from n - 1 down to 1 to merge the fully computed child distribution into its parent.
  4. For the parent's excluded state, convolve with the sum of the child's included and excluded distributions; for the parent's included state, convolve only with the child's excluded distribution.
  5. Sum the valid counts with remainder zero for the root node and subtract one to exclude the empty subset.

Code Implementation

def count_non_adjacent_subsets(parent: list[int], nums: list[int], k: int) -> int:
    modulo = 10**9 + 7
    total_nodes = len(parent)
    # Initialize dynamic programming tables for excluding and including each node
    not_chosen = [[0] * k for _ in range(total_nodes)]
    chosen = [[0] * k for _ in range(total_nodes)]
    for node_index in range(total_nodes):
        not_chosen[node_index][0] = 1
        chosen[node_index][nums[node_index] % k] = 1
    # Process nodes from leaves up to the root
    for child_index in range(total_nodes - 1, 0, -1):
        parent_index = parent[child_index]
        child_combined = [
            (not_chosen[child_index][remainder] + chosen[child_index][remainder]) % modulo
            for remainder in range(k)
        ]
        next_not_chosen = [0] * k
        next_chosen = [0] * k
        for rem_parent in range(k):
            ways_not = not_chosen[parent_index][rem_parent]
            ways_inc = chosen[parent_index][rem_parent]
            for rem_child in range(k):
                target_rem = (rem_parent + rem_child) % k
                next_not_chosen[target_rem] = (next_not_chosen[target_rem] + ways_not * child_combined[rem_child]) % modulo
                next_chosen[target_rem] = (next_chosen[target_rem] + ways_inc * not_chosen[child_index][rem_child]) % modulo
        not_chosen[parent_index] = next_not_chosen
        chosen[parent_index] = next_chosen
    # Combine root configurations and subtract the empty subset
    total_valid = (not_chosen[0][0] + chosen[0][0] - 1 + modulo) % modulo
    return total_valid

Big(O) Analysis

Time Complexity
O(n * k^2) – Each of the n - 1 edges in the tree triggers a convolution between two remainder frequency arrays of size k, taking O(k^2) time per edge.
Space Complexity
O(n * k) – We store DP tables of size k for each of the n nodes to record remainder counts for both included and excluded cases.

Optimal Solution

Approach

The problem asks for the number of non-empty, non-adjacent subsets of nodes in a rooted tree whose values sum to a multiple of k. Because parent indices are strictly smaller than child indices, we can process nodes in reverse index order, which corresponds to a bottom-up post-order traversal. For each node, we compute dynamic programming tables representing subset sums modulo k when the node is included versus when it is not included.

Here's how the algorithm would work step-by-step:

  1. Construct adjacency lists to map each parent node to its list of direct children.
  2. Iterate backwards through nodes from n - 1 down to 0 to ensure children are evaluated before their parent.
  3. Combine the DP distributions of the children using modular convolutions for cases where the current node is chosen or not chosen.
  4. Form the state where the current node is chosen by shifting the combined children distribution by the node's value modulo k.
  5. Sum the valid configurations at the root with remainder zero, subtract one to exclude the empty subset, and return the answer modulo 10^9 + 7.

Code Implementation

def count_non_adjacent_subsets(parent, nums, k):
    modulus = 10**9 + 7
    node_count = len(parent)
    dp_not_selected = [[0] * k for _ in range(node_count)]
    dp_selected = [[0] * k for _ in range(node_count)]
    children = [[] for _ in range(node_count)]
    # Group each child under its corresponding parent node.
    for child_index in range(1, node_count):
        children[parent[child_index]].append(child_index)
    # Process tree nodes in reverse topological order from leaves to root.
    for node_index in range(node_count - 1, -1, -1):
        ways_if_not_picked = [0] * k
        ways_if_picked = [0] * k
        ways_if_not_picked[0] = 1
        ways_if_picked[0] = 1
        for child in children[node_index]:
            next_not_picked = [0] * k
            next_picked = [0] * k
            child_any = [(dp_not_selected[child][remainder] + dp_selected[child][remainder]) % modulus for remainder in range(k)]
            child_none = dp_not_selected[child]
            for remainder_a in range(k):
                val_any = child_any[remainder_a]
                val_none = child_none[remainder_a]
                for remainder_b in range(k):
                    target_remainder = (remainder_a + remainder_b) % k
                    next_not_picked[target_remainder] = (next_not_picked[target_remainder] + ways_if_not_picked[remainder_b] * val_any) % modulus
                    next_picked[target_remainder] = (next_picked[target_remainder] + ways_if_picked[remainder_b] * val_none) % modulus
            ways_if_not_picked = next_not_picked
            ways_if_picked = next_picked
        dp_not_selected[node_index] = ways_if_not_picked
        node_remainder = nums[node_index] % k
        # Shift the remainder distribution by the current node's value when selected.
        for remainder in range(k):
            dp_selected[node_index][(remainder + node_remainder) % k] = ways_if_picked[remainder]
    total_valid = (dp_not_selected[0][0] + dp_selected[0][0] - 1 + modulus) % modulus
    return total_valid

Big(O) Analysis

Time Complexity
O(n * k^2) – Each node's children distributions are convolved with the running DP array. Across all children in the tree, there are n - 1 convolutions, each taking O(k^2) time, resulting in O(n * k^2) total operations.
Space Complexity
O(n * k) – The dynamic programming tables dp_not_selected and dp_selected each require an array of size k for all n nodes, consuming O(n * k) additional space.

Edge Cases

Null or empty root node input
How to Handle:
Return a count of 1 to account for the empty subset as required by the problem statement.
Single node tree with no children
How to Handle:
Return 2 because both the empty subset and the single-node subset are valid non-adjacent subsets.
Linearly skewed tree resembling a linked list
How to Handle:
Use iterative post-order traversal or tail recursion to prevent stack overflow from deep recursion.
Star graph tree with a single root and many direct children
How to Handle:
Iterate through all children efficiently in linear time to combine their inclusion and exclusion states.
Extremely large tree resulting in subset counts exceeding standard integer limits
How to Handle:
Apply modulo arithmetic using 10 to the 9th power plus 7 at every addition and multiplication step.
Negative or zero integer values stored inside the tree nodes
How to Handle:
Treat node values purely as weights for presence or absence, as subset adjacency depends solely on graph topology.
Disconnected graphs or cyclic structures passed instead of a valid tree
How to Handle:
Assume a valid rooted tree input or maintain a visited set during traversal to prevent infinite loops.
0/257 completed