Start learning free

LESSON 233 OF 671 · SETS

Common Count in Java: Counting Shared Values with HashSet

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

    JAVA · SETS

    Common Count in Java, explained

    Problem overview

    The method commonCount(int[] a, int[] b) returns how many different values appear in both arrays. "Different" is the important word: 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 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 still one shared value. For a = [1, 2] and b = [3, 4] nothing is shared, so the answer is 0.

    Approach

    The direct way is to take each number of b and scan all of a for it. That works, but every lookup walks the whole array, and repeated values would be counted again unless you add more bookkeeping.

    A HashSet fixes both problems. It stores each value at most once, and asking whether it contains a value is fast, close to constant time on average. So the plan has two parts:

    1. Put every value of a in a set. Repeats in a collapse into one entry.
    2. Go through b. When a value is in the first set, put it in a second set. Repeats in b collapse there too.

    The size of the second set is the answer.

    The set is also the reason the code needs no special case for repeats. You never have to ask "have I counted this one before?", because adding a value to a set that already holds it does nothing. The question of which array goes in the first set is open: the count of shared values is the same either way, and putting the shorter array there keeps that set smaller.

    The lesson builds the answer in two named sets so each step does one job: setA remembers what a contains, and common remembers what has been matched. Read that way, the code is a direct translation of the problem statement.

    Step by step

    1. Create setA, an empty HashSet<Integer>. It will answer "is this value in a?" quickly.
    2. Loop over a with a for-each loop and an int named num.
    3. Inside the loop, add num to setA. Adding a value that is already there changes nothing, so [7, 7, 8] becomes the set {7, 8}.
    4. After the loop, create a second empty set named common. A set, not a counter, because a value that appears several times in b must still count once.
    5. Loop over b the same way, with an int named num.
    6. Inside that loop, if setA.contains(num) is true, add num to common. The value is then in b, where the loop found it, and in a.
    7. After the loop, return common.size().

    Tracing the second example

    For a = [7, 7, 8] and b = [7, 9, 7], the first loop leaves setA holding [7, 8]: the second 7 was ignored. Then the second loop runs:

    numin setA?common afterwards
    7true[7]
    9false[7]
    7true[7]

    The set has one value, so the method returns 1.

    The solution in Java

    class Solution {
        public int commonCount(int[] a, int[] b) {
            HashSet<Integer> setA = new HashSet<>();
            for (int num : a) {
                setA.add(num);
            }
            HashSet<Integer> common = new HashSet<>();
            for (int num : b) {
                if (setA.contains(num)) {
                    common.add(num);
                }
            }
            return common.size();
        }
    }
    

    A few Java details:

    • Why Integer and not int. Java collections hold objects, so a set of numbers is written HashSet<Integer>. Java converts between int and Integer automatically (boxing), which is why setA.add(num) accepts a plain int. You can't write HashSet<int>.
    • The imports. HashSet lives in java.util. In a standalone program you would start the file with import java.util.HashSet; or import java.util.*;.
    • Set order is not guaranteed. Printing a HashSet can show its values in an order you didn't expect. This solution only asks for the size, so order doesn't matter.
    • Values are compared by value. contains(num) boxes num and compares it with equals, so 7 matches 7 even though they are different Integer objects.

    Complexity

    With n values in a and m in b, the first loop does n additions and the second does m lookups, each close to constant time on average. The total is O(n + m). The two sets hold at most n and min(n, m) values, so the extra space is O(n + m) in the worst case. The nested-scan version would take O(n * m).

    Edge cases and common mistakes

    • Counting every match in b. Using an int count and adding 1 for each b value found in setA gives 2 for the second example instead of 1, because b holds 7 twice. The common set is what prevents it.
    • Returning setA.size(). That is the number of different values in a, not the number shared with b.
    • Negative numbers. Values from -1,000,000,000 to 1,000,000,000 all fit in an int and work in a set like any other value.
    • Using == on boxed values. Comparing two Integer objects with == compares references: with two Integer variables that both hold 1000, p == q is false while p.equals(q) is true. Let the set's contains do the comparing.

    Testing

    These inputs give the outputs shown:

    • 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.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free