Start learning free

LESSON 232 OF 285 · SETS

Common Count in JavaScript: Counting Shared Values with 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 5
    Ctrl + Enter to check

    JAVASCRIPT · SETS

    Common Count in JavaScript, explained

    Problem overview

    The method commonCount(a, b) receives two arrays of integers and returns how many different values appear in both. A value counts once, however many times it shows up in either array.

    For a = [1, 2, 3, 4] and b = [3, 4, 5], the values 3 and 4 are in both arrays, so the result is 2. For a = [7, 7, 8] and b = [7, 9, 7], the only shared value is 7. It appears twice in each array, but it counts once, so the result is 1. For a = [1, 2] and b = [3, 4] nothing is shared and the result is 0.

    Approach

    The slow way is to take every value of b and scan all of a for it. That works, but the work grows with the product of the two lengths, and duplicates still need separate handling.

    A Set fixes both problems. It stores each value at most once, and asking whether it contains a value (has) is fast, however large the set is. Putting the values of a in a set gives a quick membership test. Collecting the matches in a second set removes duplicates for free: adding a value that is already there changes nothing, so the final size is the number of different shared values.

    Step by step

    1. Build setA with new Set(a). The constructor accepts any iterable, including an array, and drops repeated values.
    2. Create the empty set common that will hold the values found in both arrays. A counter would be wrong here: a value that repeats in b would be counted more than once.
    3. Loop over b with for...of. Each value of b gets checked against setA.
    4. Test and add. If setA.has(num) is true, the value is in both arrays, so common.add(num) records it.
    5. Return common.size after the loop. Unlike an array's length, size is a property of sets and maps, not a method, so it has no parentheses.

    The solution in JavaScript

    class Solution {
        commonCount(a, b) {
            let setA = new Set(a);
            let common = new Set();
            for (let num of b) {
                if (setA.has(num)) {
                    common.add(num);
                }
            }
            return common.size;
        }
    }
    

    A few details are worth knowing:

    • for...of gives values. It walks over the values of an array. for...in would give the indices as strings, which is a common slip.
    • Sets compare with strict equality. Numbers and strings are different values, so new Set([1, "1"]).size is 2. The lesson's inputs are all numbers, so this only matters if you mix types.
    • has and add are not array methods. An array has includes and push. Calling setA.includes(num) throws a TypeError.
    • Adding twice is harmless. common.add(7) twice leaves one 7, which is exactly the behaviour the problem asks for.

    Complexity

    Time: O(n + m), where n is the length of a and m the length of b. Building setA visits each value of a once, and the loop visits each value of b once, with constant-time has and add calls on average.

    Space: O(n + m). setA can hold every value of a, and common holds at most the smaller number of different values.

    Edge cases and common mistakes

    • Counting instead of collecting. Incrementing a counter for every match gives the wrong answer when b repeats a value. With a = [5, 5, 5] and b = [5] the answer is 1, and so it is with a = [5] and b = [5, 5, 5].
    • Negative numbers and zero. They are ordinary values to a set. For a = [-1, 0] and b = [0, -1, -1] the result is 2.
    • Looping over a but checking a. The loop must go over one array and test against the set made from the other.

    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.
    • a = [5, 5, 5], b = [5] gives 1.
    • a = [-1, 0], b = [0, -1, -1] gives 2.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free