Skip to content

Commit 6402e08

Browse files
committed
Add a solution to The Earliest Moment When Everyone Become Friends
1 parent 506fbb2 commit 6402e08

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Graph/EarliestMomentFriends.swift

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/
3+
* Primary idea: Classic Union Find, union every node until the count drops down to 1.
4+
*
5+
* Time Complexity: O(nlogn), Space Complexity: O(n)
6+
*
7+
*/
8+
9+
class EarliestMomentFriends {
10+
func earliestAcq(_ logs: [[Int]], _ n: Int) -> Int {
11+
let logs = logs.sorted { $0[0] < $1[0] }
12+
13+
var roots = Array(0..<n), count = n
14+
15+
for log in logs {
16+
let time = log[0], friend1 = log[1], friend2 = log[2]
17+
18+
let root1 = find(friend1, roots)
19+
let root2 = find(friend2, roots)
20+
21+
if root1 != root2 {
22+
roots[root1] = root2
23+
count -= 1
24+
}
25+
26+
if count == 1 {
27+
return time
28+
}
29+
}
30+
31+
return -1
32+
}
33+
34+
private func find(_ node: Int, _ roots: [Int]) -> Int {
35+
var node = node
36+
37+
while node != roots[node] {
38+
node = roots[node]
39+
}
40+
41+
return node
42+
}
43+
}

0 commit comments

Comments
 (0)