Connecting Cities With Minimum Cost
Problem Statement
There are n cities, numbered from 1 to n. You are given connections, a list of two-way roads. Each road [city1, city2, cost] joins two cities and has a cost.
Choose some roads so that every city can reach every other city, at the smallest total cost. Return that total cost. If the roads cannot connect all the cities, return -1.
n, the number of cities, and connections, a list of [city1, city2, cost] roads.
A single integer: the minimum total cost to connect all cities, or -1 if that is impossible.
Take road 2–3 (1) and road 1–2 (5). Together they connect all 3 cities for 6. Using 1–3 (6) instead of 1–2 (5) would cost 7.
Cities 1 and 2 are linked to each other, and cities 3 and 4 are linked to each other, but no road joins the two pairs. Some cities cannot be reached.
Keep 1–3 (1), 4–5 (2), 4–6 (3), 2–3 (5) and 2–4 (6): 1 + 2 + 3 + 5 + 6 = 17. Road 5–6 (4) is skipped, because 5 and 6 are already connected through 4.
- • Cities are numbered from 1 to n.
- • Each road joins two cities and has a cost. Roads go both ways.
- • Limits on n, the number of roads and the costs are not confirmed (this is a premium problem), so none are given here.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Grow the connected group one city at a time, reading every road in each round
Sort roads by cost; keep a road only if its two cities are in different groups
Start the group with city 1. Each round, read every road and keep the cheapest one that has exactly one city inside the group. Add that outside city and its cost. If no road leaves the group before all cities are in, return -1.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Union-Find (DSU) translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.