Taro Logo

Number of Possible Sets of Closing Branches

#3 Most AskedHard
0 views
Topics:
GraphsBit Manipulation

There is a company with n branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads.

The company has realized that they are spending an excessive amount of time traveling between their branches. As a result, they have decided to close down some of these branches (possibly none). However, they want to ensure that the remaining branches have a distance of at most maxDistance from each other.

The distance between two branches is the minimum total traveled length needed to reach one branch from another.

You are given integers n, maxDistance, and a 0-indexed 2D array roads, where roads[i] = [ui, vi, wi] represents the undirected road between branches ui and vi with length wi.

Return the number of possible sets of closing branches, so that any branch has a distance of at most maxDistance from any other.

Note that, after closing a branch, the company will no longer have access to any roads connected to it.

Note that, multiple roads are allowed.

Example 1:

Input: n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,10]]
Output: 5
Explanation: The possible sets of closing branches are:
- The set [2], after closing, active branches are [0,1] and they are reachable to each other within distance 2.
- The set [0,1], after closing, the active branch is [2].
- The set [1,2], after closing, the active branch is [0].
- The set [0,2], after closing, the active branch is [1].
- The set [0,1,2], after closing, there are no active branches.
It can be proven, that there are only 5 possible sets of closing branches.

Example 2:

Input: n = 3, maxDistance = 5, roads = [[0,1,20],[0,1,10],[1,2,2],[0,2,2]]
Output: 7
Explanation: The possible sets of closing branches are:
- The set [], after closing, active branches are [0,1,2] and they are reachable to each other within distance 4.
- The set [0], after closing, active branches are [1,2] and they are reachable to each other within distance 2.
- The set [1], after closing, active branches are [0,2] and they are reachable to each other within distance 2.
- The set [0,1], after closing, the active branch is [2].
- The set [1,2], after closing, the active branch is [0].
- The set [0,2], after closing, the active branch is [1].
- The set [0,1,2], after closing, there are no active branches.
It can be proven, that there are only 7 possible sets of closing branches.

Example 3:

Input: n = 1, maxDistance = 10, roads = []
Output: 2
Explanation: The possible sets of closing branches are:
- The set [], after closing, the active branch is [0].
- The set [0], after closing, there are no active branches.
It can be proven, that there are only 2 possible sets of closing branches.

Constraints:

  • 1 <= n <= 10
  • 1 <= maxDistance <= 105
  • 0 <= roads.length <= 1000
  • roads[i].length == 3
  • 0 <= ui, vi <= n - 1
  • ui != vi
  • 1 <= wi <= 1000
  • All branches are reachable from each other by traveling some roads.

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 range of $n$ (the number of branches), and how are the roads represented in the 2D array (e.g., [u, v, weight])?
  2. Can there be multiple roads connecting the same pair of branches, or self-loops, and how should travel times be interpreted if so?
  3. Are all branches initially considered open, and does closing a branch mean removing it and all its incident roads from the graph?
  4. If no branches are left open (an empty set), is that considered a valid configuration, and does it count toward our total?
  5. How should we handle disconnected components or unreachable pairs of open branches when checking the $maxDistance$ constraint?

Brute Force Solution

Approach

Imagine you are tasked with deciding which business branches to close down out of a group of options, while ensuring the remaining open branches can still communicate efficiently. The brute force approach involves looking at every single possible combination of closures to see which ones meet the communication rules.

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

  1. Begin by making a complete list of every single branch in the network.
  2. Consider the first branch and make a choice: either keep it open or close it down.
  3. Move to the next branch and do the same thing: decide to keep it open or close it down.
  4. Repeat this keep-or-close decision process for every single branch in the network until every possible combination of open and closed branches is mapped out.
  5. For each unique combination of open and closed branches, test how well the remaining open branches can talk to one another.
  6. Check if every open branch can reach every other open branch within a strict limit on the number of steps or distance allowed.
  7. If a particular combination satisfies the communication rule completely, count it as a successful plan.
  8. Go through every single generated combination this way, tallying up all the successful plans, and finally output the total count of valid plans.

Code Implementation

def number_of_sets(total_branches, max_distance, roads):
    valid_plan_counter = 0
    total_combinations = 1 << total_branches
    
    # Generate all subsets of branch states to evaluate every closure combination
    for combination_mask in range(total_combinations):
        
        active_branches = []
        for branch_index in range(total_branches):
            if (combination_mask & (1 << branch_index)) == 0:
                active_branches.append(branch_index)
                
        adjacency_matrix = [[float('inf')] * total_branches for _ in range(total_branches)]
        for branch_index in range(total_branches):
            adjacency_matrix[branch_index][branch_index] = 0
            
        for road in roads:
            start_node, end_node, weight = road
            if start_node in active_branches and end_node in active_branches:
                adjacency_matrix[start_node][end_node] = min(adjacency_matrix[start_node][end_node], weight)
                adjacency_matrix[end_node][start_node] = min(adjacency_matrix[end_node][start_node], weight)
                
        for intermediate in active_branches:
            for start_node in active_branches:
                for end_node in active_branches:
                    new_distance = adjacency_matrix[start_node][intermediate] + adjacency_matrix[intermediate][end_node]
                    if new_distance < adjacency_matrix[start_node][end_node]:
                        adjacency_matrix[start_node][end_node] = new_distance
                        
        # Verify network connectivity and distance limits among remaining open branches
        is_network_valid = True
        for start_node in active_branches:
            for end_node in active_branches:
                if adjacency_matrix[start_node][end_node] > max_distance:
                    is_network_valid = False
                    break
            if not is_network_valid:
                break
                
        if is_network_valid:
            valid_plan_counter += 1
            
    return valid_plan_counter

Big(O) Analysis

Time Complexity
O(2^n * n^2) – For n branches, the algorithm generates 2^n possible subsets representing every combination of open and closed branches. For each of these 2^n combinations, it must test connectivity across the remaining open branches, which takes O(n^2) operations using a traversal or distance check. Multiplying the subset generation by the validation cost yields approximately 2^n * n^2 total operations, which simplifies to O(2^n * n^2).
Space Complexity
O(n) – The space complexity is driven by the recursion stack used to explore the binary decision of keeping or closing each branch one by one. With N branches in the network, the maximum depth of the recursive calls reaches N levels deep. Additionally, variables storing the current combination state require a constant amount of extra memory at each level. Therefore, the auxiliary space scales linearly with the input size N, leading to a space complexity of O(n).

Optimal Solution

Approach

To find all valid ways to close branches under a strict limit, the optimal strategy tests every single combination of which branches to keep open and which to close. Since the total number of branches is small, we can efficiently explore every scenario by making a simple yes-or-no decision for each branch.

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

  1. Imagine going through every single branch one by one and making a choice: either keep this branch open or close it permanently.
  2. Because every branch has two possible choices, list out every possible combination of open and closed branches.
  3. For each specific combination, calculate the total distance between all pairs of branches that remain open.
  4. Check if this total distance is within the allowed limit specified in the problem.
  5. If the total distance is safely within the limit, count this combination as a successful strategy.
  6. Repeat this checking process for every single combination of open and closed branches.
  7. Finally, add up all the successful combinations to get the total number of possible ways to set up the branches.

Code Implementation

class Solution:
    def max_active_branches(self, total_branches: int, max_distance_limit: int, branch_distances: list) -> int:
        valid_combination_count = 0
        total_combinations = 1 << total_branches

        # We iterate through every possible subset of branches to evaluate them individually.
        for combination_mask in range(total_combinations):
            current_total_distance = 0
            active_branches_list = []

            for branch_index in range(total_branches):
                if (combination_mask & (1 << branch_index)):
                    active_branches_list.append(branch_index)

            # Calculate pairwise distances for all branches kept open in this combination.
            for first_index in range(len(active_branches_list)):
                for second_index in range(first_index + 1, len(active_branches_list)):
                    branch_one = active_branches_list[first_index]
                    branch_two = active_branches_list[second_index]
                    current_total_distance += branch_distances[branch_one][branch_two]

            # We ensure the subset is only counted if the total distance stays within the limit.
            if current_total_distance <= max_distance_limit:
                valid_combination_count += 1

        return valid_combination_count

Big(O) Analysis

Time Complexity
O(n * 2^n) – The cost is driven by generating every possible combination of open and closed branches for n total branches, which results in 2^n subsets. For each of these subsets, we evaluate the pairwise distances among the remaining open branches, taking up to n * n operations in the worst case. Multiplying the number of subsets by the cost to check each subset gives approximately n^2 * 2^n operations, which simplifies to the overall time complexity of O(n * 2^n) when optimized.
Space Complexity
O(n) – The space complexity is driven by the recursion stack used to explore the binary choice of keeping or closing each branch one by one. Given N total branches, the recursive exploration reaches a maximum depth of N as it processes each branch sequentially. Therefore, the auxiliary space required for the call stack scales directly with the number of branches. This simplifies to Big O of N extra memory.

Edge Cases

Minimum number of branches where n equals 1
How to Handle:
The algorithm should correctly evaluate the single branch as a trivially valid set of size one.
Graph contains disconnected components or isolated branches
How to Handle:
Shortest path algorithms like Floyd-Warshall will naturally represent unreachable distances as infinity, which exceeds maxDistance.
All branches are closed resulting in an empty set
How to Handle:
An empty set of open branches has no pairs to violate the distance condition and must be counted as a valid subset.
MaxDistance is set to zero
How to Handle:
Only single-branch sets or subsets where open branches share a travel time of zero can form valid configurations.
Roads contain cycles and multiple paths between the same pair of branches
How to Handle:
The shortest path calculation must correctly retain the minimum travel time while ignoring redundant longer paths.
Maximum number of branches n up to the upper constraint limit
How to Handle:
Since the subset generation uses bit manipulation for 2 to the power of n, the solution must operate efficiently within time limits for small n.
Road travel times equal to maxDistance exactly
How to Handle:
The distance constraint condition must use less than or equal to comparisons to properly include paths equal to maxDistance.
Duplicate roads connecting the exact same pair of branches with different weights
How to Handle:
Graph initialization must retain only the minimum edge weight between any two directly connected branches.
0/30 completed