Start learning free

LESSON 236 OF 291 · SETS

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

    KOTLIN · SETS

    Common Count in Kotlin, explained

    Problem overview

    You get two integer arrays, a and b, and commonCount returns how many different values appear in both. Repeats don't matter: a value counts once, however often it shows up in either array.

    For a = [1, 2, 3, 4] and b = [3, 4, 5] the answer is 2, because 3 and 4 are in both. For a = [7, 7, 8] and b = [7, 9, 7] the answer is 1: 7 appears twice in each array but is one value. For [1, 2] and [3, 4] nothing is shared, so the answer is 0.

    Approach

    The slow way compares every value of a with every value of b, and you would still need to avoid counting a value twice. A set makes both problems easy. A set holds each value at most once, and asking whether it contains a value is fast.

    So the plan is:

    1. Put all values of a in a set, so "is this value in a?" becomes a quick lookup.
    2. Walk through b. Every value that is also in the first set is shared.
    3. Collect the shared values in a second set. Adding a value that is already there changes nothing, so duplicates in b can't inflate the count.
    4. The answer is the size of the second set.

    Step by step

    First, a.toHashSet() builds a HashSet<Int> from the array and the code stores it in setA. Duplicates in a disappear here: [7, 7, 8] becomes a set with two values.

    Next comes common, an empty set made with hashSetOf<Int>(). It must be a set and not a counter. If 7 appears twice in b, a counter would go up twice, while a set receives 7 twice and keeps it once.

    Then a for loop visits each num in b. Inside it, setA.contains(num) tells whether that value is in a too. If it is, common.add(num) records it. After the loop, common.size is the number of different shared values.

    The solution in Kotlin

    class Solution {
        fun commonCount(a: IntArray, b: IntArray): Int {
            val setA = a.toHashSet()
            val common = hashSetOf<Int>()
            for (num in b) {
                if (setA.contains(num)) {
                    common.add(num)
                }
            }
            return common.size
        }
    }
    

    A few Kotlin details:

    • IntArray is Kotlin's array of plain Int values. toHashSet() is available on it and returns a HashSet<Int>, so the values are boxed as it is built. That is fine here.
    • val only means the variable always refers to the same set. You can still add to common, because the set itself is mutable.
    • Calling common.add(num) returns a Boolean: true if the value was new. The code ignores it, so a repeated value is simply not added again.
    • setA.contains(num) can also be written num in setA, which does the same thing.
    • A HashSet does not keep the order of its values. Printing intArrayOf(7, 7, 8).toHashSet() gives [8, 7]. The answer here only needs the size, so order doesn't matter.

    Complexity

    With n values in a and m in b, building setA takes O(n) and the loop does O(m) lookups, each O(1) on average, so the time is O(n + m). The two sets can hold up to n and min(n, m) values, so the extra space is O(n + m) in the worst case.

    Edge cases and common mistakes

    • Counting every match. Incrementing a counter for each value of b found in a gives 2 for the second example's b of [7, 9, 7] instead of 1. The second set is what prevents that.
    • Counting only one side. If a has duplicates but you loop over a instead of putting it in a set, the same mistake appears from the other side. Using a set for the shared values avoids it whichever array you loop over.
    • Values at the limits. Numbers up to a billion in size fit in Int, and sets only compare values, so nothing special is needed.
    • No overlap. The loop never adds anything, and common.size is 0.

    Testing

    These calls give the results shown:

    • commonCount(intArrayOf(1, 2, 3, 4), intArrayOf(3, 4, 5)) returns 2.
    • commonCount(intArrayOf(7, 7, 8), intArrayOf(7, 9, 7)) returns 1.
    • commonCount(intArrayOf(1, 2), intArrayOf(3, 4)) returns 0.
    • commonCount(intArrayOf(-1000000000, 1000000000), intArrayOf(1000000000, 1000000000, -1000000000)) returns 2.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free