Network Cable Cost - Problem

A company has n offices numbered 0 to n - 1. You can install network cables between offices.

You are given a 2D array cables where cables[i] = [u, v, cost] represents a cable option connecting office u to office v with installation cost cost.

Return the minimum total cost to connect all offices, or -1 if it's impossible.

Input & Output

Example 1
$ Input: n=4, cables=[[0,1,10],[0,2,6],[0,3,5],[1,3,15],[2,3,4]]
Output: 19
💡 Note: Pick cables (2,3,4)+(0,3,5)+(0,1,10)=19.
Example 2
$ Input: n=3, cables=[[0,1,1],[1,2,2],[0,2,3]]
Output: 3
💡 Note: Pick (0,1,1)+(1,2,2)=3.
Example 3
$ Input: n=4, cables=[[0,1,1],[2,3,2]]
Output: -1
💡 Note: Cannot connect all offices.

Constraints

  • 1 ≤ n ≤ 2×10^5
  • 0 ≤ cables.length ≤ 2×10^5
  • 0 ≤ u, v < n
  • 1 ≤ cost ≤ 10^6

Visualization

Tap to expand
Network Cable Cost INPUT Offices: n = 4 Cable Options (u,v,cost): 0 1 2 3 10 6 4 5 15 Find minimum total cost to connect all 4 offices. ALGORITHM STEPS 1 Sort by Cost 4, 5, 6, 10, 15 2 Greedy Pick Add cheapest edge if no cycle 3 Union-Find Cycle Check find(u)==find(v)? skip : add 4 Stop at n-1 Edges 3 edges connect 4 offices Execution Trace: edge cost cycle? action (2,3) 4 no ✓ add (0,3) 5 no ✓ add (0,2) 6 yes ✗ skip (0,1) 10 no ✓ add 3 edges used = n-1 ✓ DONE Total: 4 + 5 + 10 = 19 FINAL RESULT MST Cables Selected: 0 1 2 3 10 5 4 4 + 5 + 10 = 19 Minimum Total Cost: 19 💡 Key Insight: Minimum Spanning Tree (MST) gives the cheapest way to connect all nodes. Kruskal's sorts edges and picks greedily. Kruskal's: O(E log E). Prim's with heap: O(E log V). Return -1 if graph is disconnected. TutorialsPoint - Network Cable Cost | Kruskal's Algorithm Approach
Asked in
Amazon 0 Google 0
8 Views
High Frequency
~20 min Avg. Time
0 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