Problem overview
The method guestsMissing gets two arrays of names, invited and arrived, and returns how many invited guests haven't arrived yet. A guest may check in more than once and still counts as one guest. Someone who wasn't invited may check in too, and that doesn't change the answer.
With invited = ["Ava", "Leo", "Mia", "Zoe"] and arrived = ["Leo", "Zoe"], the answer is 2: Ava and Mia are still missing. With invited = ["Ava", "Leo"] and arrived = ["Leo", "Max", "Leo"], the answer is 1. Leo checked in twice but is one guest, Max wasn't invited, and only Ava is missing. With invited = ["Sam", "Kim"] and nobody arrived, the answer is 2.
Approach
Think of it as crossing names off a list. At the start every invited guest is missing. Each arrival crosses one name off, and what is left at the end is the answer.
A Set fits this well. delete on a set removes the value if it is there, and does nothing, with no error, if it isn't. That one behaviour covers both tricky cases. An uninvited guest isn't in the set, so deleting them changes nothing. A guest who checks in twice is removed the first time, and the second deletion changes nothing.
Step by step
- Build the set of missing guests from
invitedwithnew Set(invited), usinglet. - Loop over the arrivals with
for (let name of arrived).for...ofgives the values of an array. - Delete each name from the set.
- Return the size of the set after the loop. What is left are the invited guests who never checked in.
The solution in JavaScript
class Solution {
guestsMissing(invited, arrived) {
let missing = new Set(invited);
for (let name of arrived) {
missing.delete(name);
}
return missing.size;
}
}
A set counts its values with size, not length. Deleting never needs a has check first.
Another way
You can flip the idea: put the arrivals in a set, then keep only the invited names that aren't in it, and count them. It gives 2, 1 and 2 on the same three examples:
function viaFilter(invited, arrived) {
const here = new Set(arrived);
return invited.filter(name => !here.has(name)).length;
}
Here the set answers "has this person arrived?" quickly, and filter builds an array of the names that fail that check, so the count comes from the array's length. Both versions are correct. The lesson's version is the one to write in the editor, because its steps lead to it, and it never builds a second array. The set keeps the guest list free of repeats from the start, which is why a double check-in needs no special handling.
Testing
On the statement's three examples, the method returns:
2
1
2
Common mistakes
- Returning
invited.length - arrived.length. That breaks as soon as someone checks in twice or wasn't invited. In the second example it gives 2 - 3 = -1 instead of 1. - Using
missing.length. A set has nolength, so you getundefined. Usesize. - Adding instead of deleting. Building a set of arrivals and counting it answers a different question: how many different people came, not how many invited guests are missing.
