Problem overview
The function commonCount receives two slices of integers, a and b, and returns how many different values appear in both. A value counts once, no matter how many times it shows up in either slice.
For a = [1, 2, 3, 4] and b = [3, 4, 5] the answer is 2: the values 3 and 4 are in both slices. For a = [7, 7, 8] and b = [7, 9, 7] the answer is 1, because 7 is the only shared value and it counts once even though it appears twice on each side.
Approach: a set for one slice, a lookup for the other
The direct way is to compare every element of a with every element of b. That works, but it repeats a lot of work and needs extra care so duplicates are not counted twice.
A set makes both problems disappear. A set stores each value once and answers "is this value in here?" quickly. Go has no built-in set type, but a map does the job: map[int]bool uses the values as keys, and the bool is only a marker.
The plan has two passes. First, put every value of a into a set. Second, walk through b and, for each value that is in the first set, record it in a second set. Because the second set also keeps each value once, its size is the answer.
Step by step
- Create
setAas an emptymap[int]bool{}, declared with:=. - Loop over
awithrange. Each turn gives an index and a value; the index is not needed, so it is dropped with_. - Store each value:
setA[num] = true. A repeated value writes to the same key again, so duplicates inacollapse into one entry. - Create
common, a second emptymap[int]bool{}. It will hold the values found in both slices. - Loop over
b. - Check each value against
setA. WhensetA[num]istrue, setcommon[num] = true. - Return
len(common), the number of keys in the map.
The solution in Go
func commonCount(a []int, b []int) int {
setA := map[int]bool{}
for _, num := range a {
setA[num] = true
}
common := map[int]bool{}
for _, num := range b {
if setA[num] {
common[num] = true
}
}
return len(common)
}
Go details that make this work:
- Missing keys read as the zero value. For a
map[int]bool, a key that was never stored reads asfalse. That is whyif setA[num]needs no separate "is the key present?" test. Reading a missing key does not add it: afterm := map[int]bool{5: true}, bothm[5]andm[6]can be read, they givetrueandfalse, andlen(m)stays 1. rangeover a slice yields the index first and the value second. The blank identifier_discards the index; Go rejects unused variables, sofor i, num := range awould not compile ifiwere never used, andfor num := range awould give the indices, not the values.lenof a map is its number of keys, which here is the number of distinct shared values.- The map literal
map[int]bool{}creates a map that is ready to use. A map declared asvar m map[int]boolisnil, and writing to it panics.
Complexity
Time: O(n + m), where n and m are the lengths of a and b. Each slice is visited once, and a map insert or lookup takes constant time on average.
Space: O(n + m). setA holds up to n keys and common up to the smaller of the two distinct counts.
Edge cases and common mistakes
- Counting matches instead of values. If the second loop added 1 to a counter for each match,
a = [7, 7, 8]andb = [7, 9, 7]would give 2 instead of 1. Recording the value in a set avoids this. - No shared values.
a = [1, 2]andb = [3, 4]returns 0, becausecommonstays empty. - Negative numbers and large values are ordinary keys. Anything from -1,000,000,000 to 1,000,000,000 fits in an
int. - Mixing up the roles. Checking
bagainstsetAis enough. The result is the same if the slices swap places.
Testing
a = [1, 2, 3, 4],b = [3, 4, 5]gives2.a = [7, 7, 8],b = [7, 9, 7]gives1.a = [1, 2],b = [3, 4]gives0.
