Find All People With Secret LeetCode solution in JavaScript

1
var findAllPeople = function (n, meetings, firstPerson) {
2
const timeToMeeting = mapSortedTimeToMeetings(meetings);
3

4
const peopleThatCurrentlyHaveSecret = new Set([0, firstPerson]);
5
for (const peopleInMeetings of timeToMeeting.values()) {
6
const personToMeetingsWithPeople =
7
mapPeopleToPeopleTheyAreHavingMeetingsWith(peopleInMeetings);
8
let peopleInMeetingsWithSecret = findPeopleThatHaveTheSecret(
9
peopleInMeetings,
10
peopleThatCurrentlyHaveSecret
11
);
12

13
// BFS algorithm
14
while (peopleInMeetingsWithSecret.size > 0) {
15
const nextPeopleInMeetingsWithSecret = new Set();
16
for (const attendee of peopleInMeetingsWithSecret) {
17
for (const personInMeetingWithAttendee of personToMeetingsWithPeople[
18
attendee
19
]) {
20
// only add new people that have the secret otherwise there will be an
21
// infinite loop
22
if (!peopleThatCurrentlyHaveSecret.has(personInMeetingWithAttendee)) {
23
nextPeopleInMeetingsWithSecret.add(personInMeetingWithAttendee);
24
peopleThatCurrentlyHaveSecret.add(personInMeetingWithAttendee);
25
}
26
}
27
}
28
peopleInMeetingsWithSecret = nextPeopleInMeetingsWithSecret;
29
}
30
}
31
return [...peopleThatCurrentlyHaveSecret];
32
};
33

34
// groups all the meetings by time
35
// keys (time) is sorted in ascending order
36
function mapSortedTimeToMeetings(meetings) {
37
meetings.sort((a, b) => a[2] - b[2]);
38

39
const timeToMeeting = new Map();
40
for (const [person1, person2, time] of meetings) {
41
if (!timeToMeeting.has(time)) {
42
timeToMeeting.set(time, []);
43
}
44
timeToMeeting.get(time).push([person1, person2]);
45
}
46
return timeToMeeting;
47
}
48

49
// creates an adjacency list of people and people they are having meetings with
50
function mapPeopleToPeopleTheyAreHavingMeetingsWith(peopleInMeetings) {
51
const personToMeetingsWithPeople = {};
52
for (const [person1, person2] of peopleInMeetings) {
53
if (!personToMeetingsWithPeople[person1]) {
54
personToMeetingsWithPeople[person1] = [];
55
}
56
if (!personToMeetingsWithPeople[person2]) {
57
personToMeetingsWithPeople[person2] = [];
58
}
59
personToMeetingsWithPeople[person1].push(person2);
60
personToMeetingsWithPeople[person2].push(person1);
61
}
62
return personToMeetingsWithPeople;
63
}
64

65
// finds all the people that are in meetings that have the secret
66
// set data structue is used so that people are not duplicated
67
function findPeopleThatHaveTheSecret(
68
peopleInMeetings,
69
peopleThatCurrentlyHaveSecret
70
) {
71
const peopleInMeetingsWithSecret = new Set();
72
for (const peopleInMeeting of peopleInMeetings) {
73
for (const person of peopleInMeeting) {
74
if (peopleThatCurrentlyHaveSecret.has(person)) {
75
peopleInMeetingsWithSecret.add(person);
76
}
77
}
78
}
79
return peopleInMeetingsWithSecret;
80
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0