874906. Minimum cost to connect all houses in a city

Medium

Minimum cost to connect all houses in a city

Summary

The problem is about finding the minimum cost to connect all houses in a city, given that each connection between two houses costs a certain amount and there are no restrictions on which houses can be connected. This is an optimization problem that involves graph theory concepts.

Detailed Explanation

To solve this problem, we can use Kruskal's algorithm, which is used to find the minimum spanning tree of a graph. The idea is to sort all the edges in non-decreasing order of their weights and then pick the smallest unselected edge. If it doesn't form a cycle with the already selected edges, include it; otherwise, discard it.

Here are the steps:

  1. Initialize an empty graph G and add all houses as nodes.
  2. Create a list E to store all possible connections between houses (edges).
  3. Sort the edges in non-decreasing order of their weights.
  4. Iterate over the sorted edges and pick the smallest unselected edge.
  5. If it doesn't form a cycle with the already selected edges, include it; otherwise, discard it.
  6. Repeat step 4 until all houses are connected.
  7. The total cost is the sum of the weights of all included edges.

Here's an ASCII art diagram to illustrate the process:

   A---B---C
  /       \
 D         E
|           |
 F         G

Time complexity: O(ElogE) where E is the number of edges. Space complexity: O(V + E), where V is the number of vertices (houses).

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Input graph represented as an adjacency list
        Map<Integer, List<Edge>> graph = new HashMap<>();
        // Add edges to the graph
        graph.put(0, Arrays.asList(new Edge(0, 1, 4), new Edge(0, 2, 3)));
        graph.put(1, Arrays.asList(new Edge(1, 2, 2)));
        graph.put(2, Arrays.asList(new Edge(2, 3, 10)));

        // Find minimum spanning tree using Kruskal's algorithm
        List<Edge> mst = new ArrayList<>();
        for (Edge edge : getEdges(graph)) {
            if (!isCycle(edge, graph, mst)) {
                mst.add(edge);
            }
        }

        System.out.println("Minimum cost: " + calculateCost(mst));
    }

    static class Edge {
        int from;
        int to;
        int weight;

        public Edge(int from, int to, int weight) {
            this.from = from;
            this.to = to;
            this.weight = weight;
        }
    }

    static List<Edge> getEdges(Map<Integer, List<Edge>> graph) {
        List<Edge> edges = new ArrayList<>();
        for (List<Edge> edgeList : graph.values()) {
            edges.addAll(edgeList);
        }
        return edges;
    }

    static boolean isCycle(Edge edge, Map<Integer, List<Edge>> graph, List<Edge> mst) {
        int parent = getParent(edge.from, graph, mst);
        if (parent == -1) {
            return false; // Edge forms a cycle
        } else {
            return true;
        }
    }

    static int getParent(int node, Map<Integer, List<Edge>> graph, List<Edge> mst) {
        for (Edge edge : mst) {
            if (edge.from == node || edge.to == node) {
                return edge.from;
            }
        }
        return -1; // Node is not connected
    }

    static int calculateCost(List<Edge> mst) {
        int cost = 0;
        for (Edge edge : mst) {
            cost += edge.weight;
        }
        return cost;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.