Start learning free

LESSON 236 OF 285 · SETS

Common Count in Go: Counting Shared Values with Map Sets

Practice Read the full explanation

Given two arrays of integers, a and b, return how many different values appear in both of them.

A value counts only once, however many times it appears in a or in b.

 

Example 1:

Input: a = [1, 2, 3, 4], b = [3, 4, 5]
Output: 2
Explanation: 3 and 4 are in both. 1 and 2 are only in a, and 5 is only in b.

Example 2:

Input: a = [7, 7, 8], b = [7, 9, 7]
Output: 1
Explanation: 7 is the only value in both. It appears twice in each, but it counts once.

Example 3:

Input: a = [1, 2], b = [3, 4]
Output: 0
Explanation: No value is in both.

 

Constraints:

  • a and b each have at least one number.
  • Every number is between -109 and 109.
STEP 1 OF 7
    Ctrl + Enter to check

    GO · SETS

    Common Count in Go, explained

    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

    1. Create setA as an empty map[int]bool{}, declared with :=.
    2. Loop over a with range. Each turn gives an index and a value; the index is not needed, so it is dropped with _.
    3. Store each value: setA[num] = true. A repeated value writes to the same key again, so duplicates in a collapse into one entry.
    4. Create common, a second empty map[int]bool{}. It will hold the values found in both slices.
    5. Loop over b.
    6. Check each value against setA. When setA[num] is true, set common[num] = true.
    7. 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 as false. That is why if setA[num] needs no separate "is the key present?" test. Reading a missing key does not add it: after m := map[int]bool{5: true}, both m[5] and m[6] can be read, they give true and false, and len(m) stays 1.
    • range over a slice yields the index first and the value second. The blank identifier _ discards the index; Go rejects unused variables, so for i, num := range a would not compile if i were never used, and for num := range a would give the indices, not the values.
    • len of 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 as var m map[int]bool is nil, 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] and b = [7, 9, 7] would give 2 instead of 1. Recording the value in a set avoids this.
    • No shared values. a = [1, 2] and b = [3, 4] returns 0, because common stays 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 b against setA is enough. The result is the same if the slices swap places.

    Testing

    • a = [1, 2, 3, 4], b = [3, 4, 5] gives 2.
    • a = [7, 7, 8], b = [7, 9, 7] gives 1.
    • a = [1, 2], b = [3, 4] gives 0.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free