Cheapest Road Plan to Connect Every Fulfillment Center

Last updated: November 29, 2026

Quick Overview

Given n fulfillment centers labeled 0 to n-1 and a list of candidate roads (u, v, cost), choose roads so every center is reachable from every other at minimum total cost. Return the cost, or -1 if the candidates cannot connect them all.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Given n fulfillment centers labeled 0 to n-1 and a list of candidate roads (u, v, cost), choose roads so every center is reachable from every other at minimum total cost. Return the cost, or -1 if the candidates cannot connect them all.

A minimum spanning tree problem in the style Amazon uses for network and logistics planning. The interviewer checks that you identify MST, implement Kruskal with a correct union-find (path compression and union by rank), and detect a disconnected graph.

What the Interviewer Expects
  • Recognize the minimum spanning tree formulation
  • Implement union-find with path compression and union by rank
  • Sort edges and stop after n - 1 accepted edges
  • Detect disconnection when fewer than n - 1 edges are accepted
  • Compare Kruskal with Prim for dense graphs
Key Topics to Cover
Minimum Spanning Tree
Union Find
Kruskal
Greedy
Graphs
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Some roads already exist for free; how do you incorporate them?
  • How would you find the second best plan in case the best one is blocked?
  • When would Prim with a heap beat Kruskal?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

n >= 1. Edges are undirected tuples with non-negative integer cost; duplicates and self loops may appear. Return the minimum total cost, 0 for n = 1, and -1 if not connectable....

High-Level Design

Kruskal: sort edges by cost and add each edge whose endpoints are in different components, merging the components. The cut property guarantees the cheapest edge crossing any cut belongs to some MST, s...


Submit Your Answer
Markdown supported