Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

The cheapest node in each group

Medium · Target 15 minutes · Graphs

An undirected graph has n nodes numbered 0 to n − 1 and a list of edges. Node i has the value values[i], which may be negative. For each connected group of nodes take its smallest value, and return the sum of those minimums.

Think of the groups as networks of offices that share a supplier: each network needs one supplier, and the cost of supplying everyone is the sum of the cheapest quote in each network.

Examples

InputOutputWhy
n = 8, edges = [[0,1],[1,2],[0,2],[3,4],[5,6],[3,7]], values = [7,3,9,4,8,6,2,5]9Groups {0,1,2}, {3,4,7} and {5,6}: minimums 3 + 4 + 2.
n = 3, edges = [], values = [5,1,4]10Every node is its own group.
n = 4, edges = [[0,1],[1,2],[2,3]], values = [3,-2,8,0]-2One group; its minimum is negative.

Constraints

  • 1 ≤ n ≤ 10⁴
  • 0 ≤ edges.length ≤ 2 · 10⁴
  • −10⁶ ≤ values[i] ≤ 10⁶

Hints

Hint 1

Find the connected components: every unvisited node starts a search that marks its whole group.

Hint 2

While a search runs, keep the smallest value it has seen.

Hint 3

When the search finishes, add that minimum to the answer.

Where people lose marks

  • Initialising each group's minimum to 0, which is wrong when values can be negative and when all are positive.
  • Adding every node's value rather than one minimum per group.
  • Forgetting isolated nodes: they are groups of one.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.