Leetcode: 2092. Find All People With Secret

Problem Statement

from typing import List


class Solution:
    def findAllPeople(
        self, n: int, meetings: List[List[int]], firstPerson: int
    ) -> List[int]:
        p = [i for i in range(n)]

        def find(u):
            if p[u] != u:
                p[u] = find(p[u])
            return p[u]

        def union(u, v):
            p[find(u)] = p[find(v)]

        union(0, firstPerson)

        m = {t: [] for _, _, t in meetings}
        for u, v, t in meetings:
            m[t].append((u, v))

        for t in sorted(m):
            vs = set()
            for u, v in m[t]:
                union(u, v)
                vs.add(u)
                vs.add(v)
            for u in vs:
                if find(u) != find(0):
                    p[u] = u

        return [u for u in range(n) if find(u) == find(0)]


assert Solution().findAllPeople(6, [[1, 2, 5], [2, 3, 8], [1, 5, 10]], 1) == [
    0,
    1,
    2,
    3,
    5,
]
assert Solution().findAllPeople(4, [[3, 1, 3], [1, 2, 2], [0, 3, 3]], 3) == [0, 1, 3]
assert Solution().findAllPeople(5, [[3, 4, 2], [1, 2, 1], [2, 3, 1]], 1) == [
    0,
    1,
    2,
    3,
    4,
]