Start learning free

LESSON 236 OF 291 · SETS

Common Count in Scala: 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

    SCALA · SETS

    Common Count in Scala, explained

    Problem overview

    The method commonCount receives two arrays of integers, a and b, 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 answer is 2, because only 3 and 4 are in both. For a = [7, 7, 8] and b = [7, 9, 7] the answer is 1: 7 is the only shared value, and its repeats don't add to the count. For a = [1, 2] and b = [3, 4] nothing is shared, so the answer is 0.

    Approach: a set for lookups, a set for results

    The slow way compares every value of b with every value of a. A set avoids that: it answers "is this value in here?" in roughly constant time, and it never stores the same value twice. That gives two jobs for two sets:

    • one set holds the values of a, so each value of b can be checked quickly;
    • another set collects the shared values, and because a set ignores duplicates, a value found several times still counts once.

    A plain counter would be wrong here. With b = [7, 9, 7] a counter would add 1 for each 7 and report 2.

    Step by step

    1. Build setA from the values of a. Building the set also removes the duplicates inside a.
    2. Create the empty set common. It will gather the values found in both arrays.
    3. Loop over b with for (num <- b). Every value of the second array gets checked against the first.
    4. Test membership. Inside the loop, setA.contains(num) is true when the value is also in a. Then add it to common with +=.
    5. Return common.size after the loop. It is the number of distinct shared values.

    The solution in Scala

    class Solution {
        def commonCount(a: Array[Int], b: Array[Int]): Int = {
            val setA = scala.collection.mutable.Set[Int](a: _*)
            val common = scala.collection.mutable.Set[Int]()
            for (num <- b) {
                if (setA.contains(num)) {
                    common += num
                }
            }
            return common.size
        }
    }
    

    Scala details worth knowing:

    • Mutable versus immutable sets. A plain Set in Scala is immutable, and += on a val holding one wouldn't compile. The lesson uses scala.collection.mutable.Set, which changes in place. The val only means the name always refers to the same set.
    • Passing an array as separate values. Set[Int](a: _*) hands the elements of a to the set's constructor one by one. Scala 3.5 still accepts this spelling but prints a warning that x: _* is no longer supported and suggests x*. The code runs either way.
    • += on a set. Adding a value that is already present changes nothing, which is exactly what makes repeated matches count once.
    • return. In Scala the last expression of a block is its value, so common.size alone would also work. The lesson writes return explicitly.

    Complexity

    Let a have n values and b have m. Building setA takes O(n) and the loop does m lookups and at most m insertions, each O(1) on average, so the time is O(n + m). The two sets hold at most n and min(n, m) values, so the space is O(n + m) in the worst case.

    Edge cases and common mistakes

    • Counting every match. Incrementing a counter for each match of b overcounts when b has repeats. Use the second set.
    • Duplicates in a. They are harmless: setA stores each value once.
    • Extreme values. Values at the limits, such as -1000000000 and 1000000000, fit in an Int and work like any other.
    • Using an immutable set. Set[Int]() without the mutable prefix is immutable, so the loop couldn't add to it with += on a val.

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