The Connecting Cities With Minimum Cost interview question is a classic graph optimization problem. Imagine you are given N cities, and some cities can be connected with roads. Each connection has a specific cost associated with it. The goal is to find the minimum total cost to connect all cities such that every city is reachable from every other city (either directly or indirectly). If it is impossible to connect all cities, you must return -1. This is a direct application of finding a Minimum Spanning Tree (MST) in a graph.
Amazon and other logistics-heavy companies frequently ask the Connecting Cities With Minimum Cost coding problem because it mirrors real-world infrastructure planning. It tests a candidate's ability to model problems using graphs and their understanding of greedy algorithms. Interviewers want to see if you can efficiently handle connectivity and cycle detection in a network.
This problem primarily uses the Union Find, Graph, Heap (Priority Queue), Minimum Spanning Tree interview pattern. There are two standard algorithms to solve this:
Suppose we have 3 cities (1, 2, 3) and roads:
Using a greedy approach (Kruskal's):
Master the Union-Find data structure with path compression and union by rank. It is one of the most powerful tools for solving connectivity and grouping problems efficiently in a coding interview.