LeetCode solutions

2213. Find All People With Secret

My accepted Python solution to LeetCode problem 2213, Find All People With Secret, running in 412ms.

  • Difficulty: Hard
  • Python
  • Runtime 412ms
  • Memory 56.6MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 412ms, memory 56.6MB, accepted 2025-12-29.

python
class Solution:
    def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
        # Union-Find with path compression and union by rank
        parent = list(range(n))
        rank = [0] * n
        
        def find(x):
            if parent[x] != x:
                parent[x] = find(parent[x])
            return parent[x]
        
        def union(x, y):
            px, py = find(x), find(y)
            if px == py:
                return
            if rank[px] < rank[py]:
                px, py = py, px
            parent[py] = px
            if rank[px] == rank[py]:
                rank[px] += 1
        
        # Person 0 and firstPerson know the secret at time 0
        union(0, firstPerson)
        
        # Group meetings by time
        from collections import defaultdict
        meetings_by_time = defaultdict(list)
        for x, y, t in meetings:
            meetings_by_time[t].append((x, y))
        
        # Process meetings in chronological order
        for t in sorted(meetings_by_time.keys()):
            # Get all people involved in meetings at this time
            people = set()
            for x, y in meetings_by_time[t]:
                people.add(x)
                people.add(y)
                union(x, y)
            
            # Reset people who don't know the secret
            secret_root = find(0)
            for person in people:
                if find(person) != secret_root:
                    parent[person] = person
                    rank[person] = 0
        
        # Return all people who know the secret
        secret_root = find(0)
        return [i for i in range(n) if find(i) == secret_root]

Source