Find All People With Secret

HardGraphsunion find

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n people labeled 0 to n - 1. Person 0 knows a secret and tells it to firstPerson at time 0. You are given meetings, where meetings[i] = [x_i, y_i, time_i] means persons x_i and y_i meet at time time_i. Whenever two people meet and either of them knows the secret, both know it afterwards. Sharing is **instantaneous**: within the same time, a person who just learned the secret can pass it on in another meeting at that same time. Secrets never travel backwards in time. Return the list of all people who know the secret after every meeting has happened, sorted in **ascending** order.

Examples

Input: n = 6, meetings = [[1,2,3],[2,4,5],[3,4,2]], firstPerson = 1
Output: [0,1,2,4]
At time 2, persons 3 and 4 meet but neither knows. At time 3, person 1 tells 2. At time 5, person 2 tells 4. Person 3 never learns it.
Input: n = 5, meetings = [[2,3,1],[1,2,1]], firstPerson = 1
Output: [0,1,2,3]
Both meetings happen at time 1, so the secret flows 1 -> 2 -> 3 instantly, regardless of list order.

Constraints

  • `2 <= n <= 10^5`
  • `0 <= meetings.length <= 10^5`
  • `0 <= x_i, y_i <= n - 1`, `x_i != y_i`
  • `1 <= time_i <= 10^5`
  • `1 <= firstPerson <= n - 1`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More union find problems