oneby7

Advanced Graphs Minimum spanning trees

486. Minimum Spanning Tree Weight

Medium

You are given a connected undirected graph with n vertices, numbered from 0 to n - 1. Each row edges[i] = [u, v, w] is an edge of weight w between vertices u and v. Two edges can join the same two vertices, and an edge can join a vertex to itself.

A spanning tree is a set of n - 1 edges of the graph that connects all the vertices, so every vertex can reach every other one along these edges. Its weight is the sum of the weights of its edges. Return the smallest weight a spanning tree of the graph can have.

Example 1

431242601234

Input: n = 5 edges = [[0, 1, 4], [0, 2, 3], [1, 2, 1], [1, 3, 2], [2, 3, 4], [3, 4, 2], [2, 4, 6]]

Output: 8

Explanation: The cheapest spanning tree takes [1, 2, 1], [1, 3, 2], [3, 4, 2] and [0, 2, 3]. Its weight is 1 + 2 + 2 + 3 = 8.

Example 2

60213012

Input: n = 3 edges = [[0, 1, 6], [1, 1, 0], [1, 0, 2], [2, 2, 1], [1, 2, 3]]

Output: 5

Explanation: Of the two edges between vertices 0 and 1, the tree takes the one of weight 2. It adds [1, 2, 3], so the weight is 5. The edges [1, 1, 0] and [2, 2, 1] join a vertex to itself and connect nothing.

Example 3

10⁹10⁹10⁹10⁹0123

Input: n = 4 edges = [[0, 1, 1000000000], [1, 2, 1000000000], [2, 3, 1000000000], [3, 0, 1000000000]]

Output: 3000000000

Explanation: The four edges form a loop, and any three of them connect the vertices. Each weighs 109, so the weight is 3 × 109.

Check your understanding

Work out the answer for this input before you write any code.

n = 4 edges = [[0, 1, 1], [1, 2, 2], [0, 2, 2], [2, 3, 7], [0, 3, 9]]

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 105
  • edges[i] = [u, v, w], with 0 ≤ u, v < n and 0 ≤ w ≤ 109
  • The graph is connected.
  • Two edges can join the same two vertices, and an edge can join a vertex to itself.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.