Number of Possible Sets of Closing Branches - Problem

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] = [u_i, v_i, w_i] represents the undirected road between branches u_i and v_i with length w_i.

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,1]]
Output: 5
💡 Note: Valid subsets: {0}, {1}, {2}, {0,1}, {0,2}. Subset {1,2} invalid (distance 10 > 5). Subset {0,1,2} invalid (distance 10 > 5).
Example 2 — All Connected Within Distance
$ Input: n = 3, maxDistance = 10, roads = [[0,1,1],[1,2,1],[2,0,1]]
Output: 7
💡 Note: All 7 possible subsets are valid since max distance is 2, which is ≤ 10.
Example 3 — Linear Chain
$ Input: n = 4, maxDistance = 4, roads = [[0,1,3],[1,2,3],[2,3,3]]
Output: 8
💡 Note: Single branches and adjacent pairs are valid. Longer chains exceed maxDistance.

Constraints

  • 2 ≤ n ≤ 15
  • 1 ≤ maxDistance ≤ 109
  • 0 ≤ roads.length ≤ 1000
  • roads[i].length == 3
  • 0 ≤ ui, vi ≤ n-1
  • ui ≠ vi
  • 1 ≤ wi ≤ 109
  • All branches are initially reachable from each other

Visualization

Tap to expand
Number of Possible Sets of Closing BranchesInput: Branch Network0122110Valid Subsets (Distance ≤ 5){0}{1}{2}{0,1}: d=2{0,2}: d=1Invalid Subsets{1,2}: d=10 > 5{0,1,2}: d=10 > 5Algorithm: Try all 2^n - 1 = 7 subsetsUse Floyd-Warshall to compute shortest paths, then check each subsetResult: 5 valid subsetsmaxDistance = 5, so count subsets where all distances ≤ 5
Understanding the Visualization
1
Input Graph
n=3 branches with roads and maxDistance=5
2
Compute Distances
Find shortest paths between all branch pairs
3
Check Subsets
Count subsets where max distance ≤ 5
Key Takeaway
🎯 Key Insight: Use bitmasks to enumerate all subsets and precompute distances for efficiency
Asked in
Amazon 25 Microsoft 18 Google 12
12.0K Views
Medium Frequency
~35 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen