Problem Description
There are n people numbered from 0 to n-1. Person 0 initially knows a secret and immediately shares it with firstPerson at time 0. A list of meetings is provided where each meeting is represented as [x, y, time] indicating that person x and person y meet at the specified time. During a meeting, if any participant knows the secret by that time, they share it with the other person. Meetings occurring at the same time allow instantaneous sharing, meaning a person can both receive and then share the secret within the same time frame. The goal is to output the list of all people who know the secret after all meetings are processed.
Key Insights
- Meetings must be processed in chronological order.
- Multiple meetings at the same time can be grouped together, and the secret can spread within the whole connected component.
- Using union-find (disjoint set union) to group people meeting at the same time helps efficiently determine connected components.
- After processing a time group, any connected component that contains a person with the secret will have all its members learn the secret.
- Reset the union-find structure for each new time group to isolate interactions.
Space and Time Complexity
Time Complexity: O(m log m + m α(n)) where m is the number of meetings and α(n) is the inverse Ackermann function (nearly constant time per union-find operation).
Space Complexity: O(n + m)
Solution
We start by sorting the meetings by time. For each set of meetings with the same time stamp, we initialize a temporary union-find structure limited to the people involved in that time slot. Within this group, we union the meeting pairs. Next, for each connected component, we check if any member already knows the secret. If so, we mark all members of that component as having the secret. After processing a time group, we clear the union-find connections and move to the next time group. Finally, we return the list of people who know the secret.