Problem overview
The function guestsMissing gets two lists of names, invited and arrived. It returns how many invited guests have not arrived yet. Three details shape the solution:
- A guest may check in more than once, but still counts as one guest.
- Someone who was not invited may check in too, and that must not change the answer.
- The names in
invitedare all different;arrivedmay be empty.
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 came twice, Max was not invited, and only Ava is missing.
Approach
Do not compare the two sizes. Subtracting the size of arrived from the size of invited gives -1 for the second example, because it counts the repeat and the uninvited guest.
Think of the invited list as a list of people still expected. Start with everyone as missing, then cross off each arrival. A HashSet fits: removing a name that is not in the set does nothing, and removing a name twice also does nothing the second time. Both awkward cases then solve themselves, with no extra if. What is left in the set at the end is exactly the invited guests who never checked in.
Step by step
- Build the set of missing guests from the invited list, with
invited.toHashSet(), in avalnamedmissing. At the start, everybody is missing. - Loop over
arrived, with the loop variablename. - Inside the loop, call
missing.remove(name). Ifnamewas invited and still in the set, it comes out. If not (an uninvited guest, or a repeat arrival),removereturnsfalseand the set stays as it was. - After the loop, return
missing.size.
The solution in Kotlin
class Solution {
fun guestsMissing(invited: List<String>, arrived: List<String>): Int {
val missing = invited.toHashSet()
for (name in arrived) {
missing.remove(name)
}
return missing.size
}
}
The call missing.remove(name) returns a Boolean, and the code ignores it, which Kotlin allows. The set is a copy: it does not change the invited list, which the caller still has. val is fine for missing, since the variable never points to another set; only the set's contents change.
The three examples give:
2
1
2
In the third, arrived is empty, so the loop does nothing and both invited guests, Sam and Kim, remain.
Complexity
Building the set takes one step per invited name, and each remove is fast, so the work is proportional to the two lists' lengths added together. The set takes space for the invited names.
Common mistakes
- Subtracting sizes. It breaks on repeats and uninvited guests, as shown above.
- Counting arrivals that are in
invited. A guest who checks in twice would be counted twice, unless you also track who was counted. - Using lists instead of a set. A list's
removeworks too, but a set's one-step check is simpler to reason about and does not scan the list for each name. - Guarding with an
ifbefore removing. It is not needed;removealready ignores a missing name.
