Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1135: Connecting Cities With Minimum Cost

In this guide, we solve Leetcode #1135 Connecting Cities With Minimum Cost in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

There are n cities labeled from 1 to n. You are given the integer n and an array connections where connections[i] = [xi, yi, costi] indicates that the cost of connecting city xi and city yi (bidirectional connection) is costi.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Union Find, Graph, Minimum Spanning Tree, Heap (Priority Queue)

Intuition

We need to repeatedly access the smallest or largest element as the input changes.

A heap provides fast insertions and removals while keeping order.

Approach

Push candidates into the heap as you scan, and pop when you need the best element.

Keep the heap size bounded if the problem requires a top-k structure.

Steps:

  • Push candidates into a heap.
  • Pop the best candidate when needed.
  • Maintain heap size or invariants.

Example

Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]] Output: 6 Explanation: Choosing any 2 edges will connect all cities so we choose the minimum 2.

Python Solution

class Solution: def minimumCost(self, n: int, connections: List[List[int]]) -> int: def find(x): if p[x] != x: p[x] = find(p[x]) return p[x] connections.sort(key=lambda x: x[2]) p = list(range(n)) ans = 0 for x, y, cost in connections: x, y = x - 1, y - 1 if find(x) == find(y): continue p[find(x)] = find(y) ans += cost n -= 1 if n == 1: return ans return -1

Complexity

The time complexity is O(m×log⁡m)O(m \times \log m)O(m×logm), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy