Scribbling

LeetCode: 1101. The Earliest Moment When Everyone Become Friends 본문

Computer Science/Coding Test

LeetCode: 1101. The Earliest Moment When Everyone Become Friends

focalpoint 2023. 9. 14. 03:47

https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

class Solution:
    def earliestAcq(self, logs: List[List[int]], n: int) -> int:

        parents = [i for i in range(n)]
        group_size = {i: 1 for i in range(n)}

        def find_parent(a):
            if parents[a] == a:
                return a
            parents[a] = find_parent(parents[a])
            return parents[a]
        
        def union(a, b):
            a, b = find_parent(a), find_parent(b)
            if a < b:
                parents[b] = a
                group_size[a] += group_size[b]
                return group_size[a]
            else:
                parents[a] = b
                group_size[b] += group_size[a]
                return group_size[b]
        
        logs.sort()
        for t, u, v in logs:
            if find_parent(u) != find_parent(v):
                if union(u, v) == n:
                    return t
        return -1