#2092

Find All People With Secret

Hard
Depth-First SearchBreadth-First SearchUnion-FindGraph TheorySortingUnion-FindGraph Theory
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

This approach uses a graph representation of the meetings and a union-find data structure to efficiently manage the sharing of secrets. We process meetings in chronological order and use union operations to group people who can share the secret.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the meetings by time.
  2. 2Step 2: Use a union-find structure to group people who meet at the same time.
  3. 3Step 3: After processing all meetings, check which groups contain people who know the secret and return them.
solution.py25 lines
1class UnionFind:
2    def __init__(self, size):
3        self.parent = list(range(size))
4    def find(self, x):
5        if self.parent[x] != x:
6            self.parent[x] = self.find(self.parent[x])
7        return self.parent[x]
8    def union(self, x, y):
9        rootX = self.find(x)
10        rootY = self.find(y)
11        if rootX != rootY:
12            self.parent[rootY] = rootX
13
14
15def findAllPeople(n, meetings, firstPerson):
16    uf = UnionFind(n)
17    meetings.sort(key=lambda x: x[2])
18    meetings.append([0, 0, 0])  # Add a dummy meeting for union-find
19    for x, y, time in meetings:
20        uf.union(x, y)
21    secret_holders = set()
22    for i in range(n):
23        if uf.find(i) == uf.find(0) or uf.find(i) == uf.find(firstPerson):
24            secret_holders.add(i)
25    return list(secret_holders)

Complexity note: The time complexity is O(n log n) due to sorting the meetings, while the union-find operations are nearly constant time, making this approach efficient.

  • 1Using union-find helps efficiently manage groups of people sharing secrets.
  • 2Processing meetings in chronological order ensures that secrets are shared as soon as possible.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.