#2959

Number of Possible Sets of Closing Branches

Hard
Bit ManipulationGraph TheoryHeap (Priority Queue)EnumerationShortest PathBit ManipulationGraph TheoryDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n³ + 2^n * n²)
Space
O(1)
O(n²)
💡

Intuition

Time O(n³ + 2^n * n²)Space O(n²)

Instead of checking all subsets, we can use a more efficient approach by leveraging the Floyd-Warshall algorithm to precompute shortest paths and then use bit manipulation to efficiently check subsets of branches.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a graph from the roads and compute the shortest paths between all pairs of branches using Floyd-Warshall.
  2. 2Step 2: For each subset of branches, check if all pairs of branches in the subset are within maxDistance using the precomputed shortest paths.
  3. 3Step 3: Count valid subsets.
solution.py37 lines
1# Full working Python code
2import itertools
3import sys
4
5def floyd_warshall(n, graph):
6    dist = [[sys.maxsize] * n for _ in range(n)]
7    for u in range(n):
8        dist[u][u] = 0
9    for u, v, w in graph:
10        dist[u][v] = min(dist[u][v], w)
11        dist[v][u] = min(dist[v][u], w)
12    for k in range(n):
13        for i in range(n):
14            for j in range(n):
15                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
16    return dist
17
18def count_possible_sets(n, maxDistance, roads):
19    graph = roads
20    dist = floyd_warshall(n, graph)
21    count = 0
22    for mask in range(1 << n):
23        valid = True
24        for i in range(n):
25            for j in range(i + 1, n):
26                if (mask & (1 << i)) and (mask & (1 << j)):
27                    if dist[i][j] > maxDistance:
28                        valid = False
29                        break
30            if not valid:
31                break
32        if valid:
33            count += 1
34    return count
35
36# Example usage
37print(count_possible_sets(3, 5, [[0, 1, 2], [1, 2, 10], [0, 2, 10]]))

Complexity note: Floyd-Warshall runs in O(n³) and checking each subset takes O(2^n * n²) due to the nested loops for pair checking.

  • 1Using bit manipulation can significantly reduce the complexity of checking subsets.
  • 2Precomputing distances allows for quick validation of branch sets.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.