All practice tasks

Coding (Algo)

Minimum Network Connection Cost

Minimum spanning tree · Medium

A planner can purchase undirected links between sites. It needs to connect every site at the lowest total cost. Links may have equal or negative costs, but a spanning tree must not contain cycles.

Return the minimum total weight of a spanning tree or null if the sites cannot all be connected.

Input

Call

  • Implement solve(input) and return the result. The provided adapter handles JSON input and output.

Input shape

A JSON object { "n": number, "edges": [number,number,number][] }.

Fields

  • n is the number of vertices with IDs 0..n-1. Every endpoint is valid. Parallel edges and self-edges are allowed; when n is 0 the edge list is empty.
  • Each entry in edges is [first,second,weight] for an undirected link.

Output

Return value

  • Return a number or null, not a set of edges.
  • For n=0 or n=1 return 0. For n>1 a spanning tree has exactly n-1 useful links.
  • Self-loops cannot contribute to a spanning tree, even with negative weight. Parallel links are independent choices.

Constraints

  • 0 <= n <= 100000 and at most 200000 edges.
  • A chain may contain 100000 vertices; do not depend on a call stack that deep.
  • Weights are integers in [-1000000000,1000000000]; the total fits exactly in Number.

Examples

Example 1

{
  "edges": [
    [
      0,
      1,
      4
    ],
    [
      1,
      2,
      2
    ],
    [
      0,
      2,
      1
    ]
  ],
  "n": 3
}

Returns

3

Use weights 1 and 2.

Example 2

{
  "edges": [
    [
      0,
      1,
      1
    ]
  ],
  "n": 3
}

Returns

null

Site 2 cannot be connected.

Required complexity

O(m log(m + 1) + n) time with near-constant amortized connectivity operations, and O(n + m) space

What this task practices

Minimum Network Connection Cost is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as medium difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.