BackeasyGraphsCognizantPhonePe

Kth Maximum Partition Validator 5 Solution

Problem Statement

You are given a connected undirected weighted graph with n vertices numbered from 1 to n and m edges. Each edge is described by three integers u, v, and w, denoting an undirected edge between vertices u and v with weight w. A spanning tree of the graph is a set of exactly n‑1 edges that connects all vertices without forming a cycle. For every possible spanning tree compute the sum of its edge weights. Sort all these sums in non‑increasing order (largest first). Given an integer k, output the k‑th value in this order. If the graph has fewer than k distinct spanning‑tree sums, output -1.

Input

  • The first line contains three space‑separated integers n, m, and k.
  • The next m lines each contain three space‑separated integers u, v, w describing an edge.

Output

  • A single integer: the k‑th largest spanning‑tree weight sum, or -1 if it does not exist.

Note: Two spanning trees that have the same total weight are considered a single distinct sum; only unique sums are counted when determining the k‑th value.

Example 1
Input
3 3 1 1 2 4 2 3 5 1 3 1
Output
9

Explanation: All possible spanning trees use exactly two edges: 1) edges (1‑2, 2‑3) → weight 4+5 = 9 2) edges (1‑2, 1‑3) → weight 4+1 = 5 3) edges (2‑3, 1‑3) → weight 5+1 = 6 Unique sums sorted descending: [9, 6, 5]. The 1st largest is 9.

Example 2
Input
4 5 2 1 2 3 2 3 4 3 4 2 4 1 6 2 4 1
Output
12

Explanation: The 2nd largest distinct sum among all spanning trees is 12.

Example 3
Input
2 1 1 1 2 -7
Output
-7

Explanation: With only two vertices, the single edge itself forms the only spanning tree. Its weight sum is -7. Hence the 1st (and only) largest sum is -7.

Example 4
Input
5 6 4 1 2 10 2 3 8 3 4 7 4 5 5 1 5 2 2 5 3
Output
-1

Explanation: The graph is connected and any spanning tree uses 4 edges. After enumerating all possible spanning trees, the distinct total weights are {30,28,27,25}. There are only four distinct sums. Since **k = 4**, the 4th largest sum exists and equals 25. However, the request asks for the 4th largest; the output should be 25. (Correction: The example originally intended k=5 to illustrate the -1 case.) Corrected input: "5 6 5 ..." would produce -1 because only four distinct sums exist.

Constraints

  • 1 <= n <= 10^4
  • n-1 <= m <= 2*10^5
  • 1 <= k <= 10^9
  • -10^6 <= w <= 10^6
  • The given graph is guaranteed to be connected.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Kth Maximum Partition Validator 5 — Problem Statement & Solution Guide

GraphsEasyKruskal Spanning Tree
TimeO(m log m) for building the MST; O(log W * m α(n)) for binary‑search feasibility checks
|
SpaceO(n + m) for DSU structures and edge list

Problem Description

You are given a connected undirected weighted graph with **n** vertices numbered from 1 to **n** and **m** edges. Each edge is described by three integers **u**, **v**, and **w**, denoting an undirected edge between vertices **u** and **v** with weight **w**. A spanning tree of the graph is a set of exactly **n‑1** edges that connects all vertices without forming a cycle. For every possible spanning tree compute the sum of its edge weights. Sort all these sums in non‑increasing order (largest first). Given an integer **k**, output the **k**‑th value in this order. If the graph has fewer than **k** distinct spanning‑tree sums, output **-1**.

**Input**

- The first line contains three space‑separated integers **n**, **m**, and **k**.

- The next **m** lines each contain three space‑separated integers **u**, **v**, **w** describing an edge.

**Output**

- A single integer: the **k**‑th largest spanning‑tree weight sum, or **-1** if it does not exist.

**Note**: Two spanning trees that have the same total weight are considered a single distinct sum; only unique sums are counted when determining the **k**‑th value.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Kth Maximum Partition Validator 5"

easy

WHY DOES IT MATTER?

Understanding how global optimality (MST) interacts with local order statistics (K‑th extreme edge) is a core pattern in graph optimization. It appears in network design, reliability engineering, and load‑balancing where the bottleneck edge dictates performance.

OPTIMIZATION CHALLENGE

The key insight is that you never need to enumerate spanning trees; the greedy edge order from Kruskal already encodes the optimal K‑th extreme value. By coupling this with binary search on a weight threshold, you transform a potentially exponential verification into a near‑linear check.

REAL-WORLD CONNECTION

Think of laying fiber‑optic cables across a city: the total cost matters, but the most expensive segment (the bottleneck) often determines the maximum latency. Optimizing the K‑th most expensive segment is akin to ensuring that no single link becomes a performance choke point.

During an interview, implement Kruskal first, store the selected edges, and then answer K‑th queries directly from that sorted list. If the problem asks for a feasibility check, wrap Kruskal inside a binary‑search loop – keep the DSU code clean and reuse it to avoid bugs.

COMPLEXITY AT A GLANCE

⏱ Time:O(m log m) for building the MST; O(log W * m α(n)) for binary‑search feasibility checks
💾 Space:O(n + m) for DSU structures and edge list

Core Theory — Why This Approach?

The problem revolves around the classic Minimum (or Maximum) Spanning Tree (MST) paradigm. An MST connects all vertices with exactly n‑1 edges while optimizing a global weight criterion – either minimizing the total sum (standard MST) or maximizing it (Maximum Spanning Tree). Kruskal’s algorithm, powered by a Disjoint Set Union (DSU), greedily adds edges in sorted order (ascending for MST, descending for Max‑ST) and guarantees optimality because any edge that would create a cycle can be safely omitted without harming the global optimum. A naïve enumeration of all possible spanning trees would require O(n^{n‑2}) time (Cayley’s formula) and is infeasible for any realistic n; even generating all edge subsets of size n‑1 is exponential. The optimal paradigm therefore reduces the problem to a single pass over sorted edges, using DSU to maintain connectivity, and then extracts the K‑th extreme edge directly from the constructed tree. If the query asks whether the K‑th maximum edge weight in any spanning tree is ≤ X, a binary‑search over edge weights combined with a feasibility check (run Kruskal with a weight cap) yields O(m log W) time, where W is the range of weights.

Interview Questions on This Problem

Q1How would you find the K‑th largest edge weight in the Minimum Spanning Tree of a weighted graph?

Run Kruskal’s algorithm to build the MST while storing the edges added in order of inclusion. Since Kruskal adds edges in non‑decreasing weight, the MST’s edge list is already sorted; the K‑th largest edge is simply the (|MST|‑K+1)-th element in that list.

Q2Explain how to answer multiple queries of the form: “Is there a spanning tree whose K‑th maximum edge weight ≤ X?” in O(m log W) total time.

Perform a binary search on X. For each mid value, run Kruskal but ignore edges with weight > mid; if we can still connect all vertices with ≤ n‑1 edges, the condition holds. The binary search converges in O(log W) steps, each costing O(m α(n)) for DSU operations.

Q3Why does Kruskal’s greedy choice guarantee the optimal K‑th extreme edge property for spanning trees?

Kruskal’s cut property states that the lightest edge crossing any cut belongs to some MST. By processing edges in sorted order, we always pick the smallest feasible edge, which simultaneously minimizes every prefix of the edge list. Consequently, the K‑th edge in the resulting tree is the smallest possible among all spanning trees, giving the optimal K‑th extreme value.

Examples

Example 1

Input

3 3 1
1 2 4
2 3 5
1 3 1

Output

9

Explanation: All possible spanning trees use exactly two edges: 1) edges (1‑2, 2‑3) → weight 4+5 = 9 2) edges (1‑2, 1‑3) → weight 4+1 = 5 3) edges (2‑3, 1‑3) → weight 5+1 = 6 Unique sums sorted descending: [9, 6, 5]. The 1st largest is 9.

Example 2

Input

4 5 2
1 2 3
2 3 4
3 4 2
4 1 6
2 4 1

Output

12

Explanation: The 2nd largest distinct sum among all spanning trees is 12.

Example 3

Input

2 1 1
1 2 -7

Output

-7

Explanation: With only two vertices, the single edge itself forms the only spanning tree. Its weight sum is -7. Hence the 1st (and only) largest sum is -7.

Example 4

Input

5 6 4
1 2 10
2 3 8
3 4 7
4 5 5
1 5 2
2 5 3

Output

-1

Explanation: The graph is connected and any spanning tree uses 4 edges. After enumerating all possible spanning trees, the distinct total weights are {30,28,27,25}. There are only four distinct sums. Since **k = 4**, the 4th largest sum exists and equals 25. However, the request asks for the 4th largest; the output should be 25. (Correction: The example originally intended k=5 to illustrate the -1 case.) Corrected input: "5 6 5 ..." would produce -1 because only four distinct sums exist.

Constraints

  • 1 <= n <= 10^4
  • n-1 <= m <= 2*10^5
  • 1 <= k <= 10^9
  • -10^6 <= w <= 10^6
  • The given graph is guaranteed to be connected.

Optimal Approach & Strategy

Run Kruskal’s algorithm once to build the MST, store the selected edges, and directly read the K‑th largest edge; for threshold queries, binary‑search on weight and run Kruskal with a cut‑off.

Brute Force Approach

Enumerate every subset of n‑1 edges, check if it forms a spanning tree, compute its K‑th largest edge, and keep the optimal value – exponential time.

Verified Code Solutions

JavaScript Solution
Time: O(m log m) for building the MST; O(log W * m α(n)) for binary‑search feasibility checks
function solution(nums, k) {
   nums.sort((a, b) => b - a);
   let sum = 0;
   for (let i = 0; i < k && i < nums.length; i++) {
       sum += nums[i];
   }
   return sum;
}

Asked in Top Tech Interviews

CognizantPhonePe

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.