Skip to content

Commit 123d634

Browse files
committed
Add solution
1 parent e6167d1 commit 123d634

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// 3608. Minimum Time for K Connected Components
2+
// You are given an integer n and an undirected graph with n nodes labeled from 0 to n - 1. This is represented by a 2D array edges, where edges[i] = [ui, vi, timei] indicates an undirected edge between nodes ui and vi that can be removed at timei.
3+
// You are also given an integer k.
4+
// Initially, the graph may be connected or disconnected. Your task is to find the minimum time t such that after removing all edges with time <= t, the graph contains at least k connected components.
5+
// Return the minimum time t.
6+
// A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.
7+
8+
9+
// Solution: Binary Search
10+
11+
// Binary search for the minimum time t.
12+
// For a time t, find the number of connected components without using edges with time <= t.
13+
14+
// Finding the number of connected components:
15+
// For each node, use DFS to visit all nodes connected to that node.
16+
// If we've already visited a node, skip it.
17+
// The count of non-visited nodes is the number of connected components.
18+
19+
// n = number of nodes
20+
// Time Complexity: O((n + edges) * log(max(time))) 931ms
21+
// Space Complexity: O(n) 144MB
22+
function minTime(n, edges, k) {
23+
const graph = Array(n).fill(0).map(() => []);
24+
let maxTime = 0;
25+
for (let [u, v, time] of edges) {
26+
graph[u].push([v, time]);
27+
graph[v].push([u, time]);
28+
maxTime = Math.max(maxTime, time);
29+
}
30+
let low = 0, high = maxTime;
31+
while (low < high) {
32+
const mid = Math.floor((low + high) / 2);
33+
if (connectedComponents(n, graph, mid) >= k) {
34+
high = mid;
35+
} else {
36+
low = mid + 1;
37+
}
38+
}
39+
return low;
40+
};
41+
42+
// Find connected components excluding edges with time <= t
43+
function connectedComponents(n, graph, t) {
44+
const seen = Array(n).fill(false);
45+
let components = 0;
46+
for (let i = 0; i < n; i++) {
47+
if (!seen[i]) {
48+
components++;
49+
dfs(i);
50+
}
51+
}
52+
return components;
53+
54+
function dfs(node) {
55+
seen[node] = true;
56+
for (let [nei, time] of graph[node]) {
57+
if (!seen[nei] && time > t) {
58+
dfs(nei);
59+
}
60+
}
61+
}
62+
}
63+
64+
// Two test cases
65+
console.log(minTime(2, [[0,1,3]], 2)) // 3
66+
console.log(minTime(3, [[0,1,2],[1,2,4]], 3)) // 4

0 commit comments

Comments
 (0)