Start learning free

LESSON 235 OF 289 · SETS

Common Count in C#: 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 5
    Ctrl + Enter to check

    C# · SETS

    Common Count in C#, explained

    Problem overview

    CommonCount receives two int[] arrays, 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.

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

    Approach: a set for lookups, a set for the answer

    A HashSet<int> stores each value at most once and answers "is this value in here?" quickly. That gives two jobs for sets:

    • Put the values of a in a set. Checking whether a value of b also appears in a becomes one fast Contains call, instead of a loop over all of a.
    • Collect the shared values in a second set. Adding a value that is already in a set does nothing, so repeated values in b can't be counted twice. A plain counter would count them twice, which is the mistake this lesson is built to avoid.

    Step by step

    1. Build setA with new HashSet<int>(a). The constructor takes any collection of ints and keeps one copy of each value, so the duplicates in a disappear here.
    2. Create an empty set named common. It will hold the values found in both arrays.
    3. Loop over b with foreach (int num in b). Every value of b gets one check against setA.
    4. Test setA.Contains(num). When it is true, num is in b (the loop found it) and in a (the set says so), so common.Add(num).
    5. Return common.Count. On a HashSet, Count is a property, not a method, so there are no parentheses.

    The solution in C#

    class Solution {
        public int CommonCount(int[] a, int[] b) {
            HashSet<int> setA = new HashSet<int>(a);
            HashSet<int> common = new HashSet<int>();
            foreach (int num in b) {
                if (setA.Contains(num)) {
                    common.Add(num);
                }
            }
            return common.Count;
        }
    }
    

    A few C# details:

    • HashSet<T> lives in System.Collections.Generic. In a file of your own, add using System.Collections.Generic; at the top.
    • Add returns a bool: true if the value was new, false if the set already had it. Starting from the set {1, 2, 3}, Add(2) gives False and Add(9) gives True, and the set then has 4 values. This lesson ignores the return value, because adding an existing value is harmless.
    • Values up to a billion in size fit in an int (largest value 2,147,483,647), and the code never does arithmetic on them, so overflow can't happen.

    Complexity

    Building setA takes one pass over a, and the loop is one pass over b with a fast lookup per value, so the time is O(n + m) for arrays of length n and m. The two sets use O(n + m) extra memory at most. Comparing every pair of values with two nested loops would take O(n × m).

    Edge cases and common mistakes

    • Counting every match. Incrementing a counter inside the loop gives 2 for a = [7], b = [7, 7] when the answer is 1. Adding to a set avoids that.
    • Duplicates in a. They are harmless, because the set built from a already merges them.
    • No shared values. common stays empty and Count is 0.
    • Negative numbers and extremes. a = [-1000000000, 1000000000] against b = [1000000000, -1000000000, 0] returns 2. Sets treat negative values like any other.

    Testing

    Inputs worth trying, with the results the solution returns:

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