Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created December 19, 2025 17:18
Show Gist options
  • Select an option

  • Save tatsuyax25/16485a83652f59b3a345befb66634a92 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/16485a83652f59b3a345befb66634a92 to your computer and use it in GitHub Desktop.
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person m
/**
* @param {number} n
* @param {number[][]} meetings
* @param {number} firstPerson
* @return {number[]}
*/
// Function to find all people connected to the first person
var findAllPeople = function(n, meetings, firstPerson) {
// Initialize an array to keep track of connections
const connected = new Array(n).fill(-1);
// Function to find the parent of a person
const find = (person) => connected[person] < 0 ? person : find(connected[person]);
// Function to connect two people
const union = (p1, p2) => {
const pp1 = find(p1), pp2 = find(p2);
// If they are already connected, return
if (pp1 === pp2) return pp1;
const r1 = connected[pp1], r2 = connected[pp2];
// Connect the two people
if (r1 <= r2) {
connected[pp1] += r2;
connected[pp2] = pp1;
} else {
connected[pp2] += r1;
connected[pp1] = pp2;
}
}
// Function to reset a person's connection
const reset = (person) => {
const parent = find(person);
if (parent === person) return;
connected[parent] -= connected[person];
connected[person] = -1;
}
// Connect the first person to the root (0)
union(0, firstPerson);
// Initialize a map to store meeting start times
const starts = {};
// Populate the map with meeting start times
for (let i = 0; i < meetings.length; i++) {
const [p1, p2, t] = meetings[i];
starts[t] = starts[t] || [];
starts[t].push(i);
}
// Get all the meeting times and sort them
const times = Object.keys(starts).map(t => +t).sort((a, b) => a - b);
// Initialize a set to store the result
const res = new Set([0, firstPerson]);
// For each meeting time
for(const time of times) {
const set = new Set();
// For each meeting starting at this time
for(const i of starts[time]) {
const [p1, p2, t] = meetings[i];
// Connect the two people in the meeting
union(p1, p2);
// Add them to the set
set.add(p1);
set.add(p2);
}
// For each person in the set
for(const p of set) {
// If the person is not connected to the root, reset their connection
if(find(p) !== find(0)) {
reset(p);
} else {
// Otherwise, add them to the result
res.add(p);
}
}
}
// Return the result as an array
return [...res];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment