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:
- Put every value of
ain a set. Repeats inacollapse into one entry. - Go through
b. When a value is in the first set, put it in a second set. Repeats inbcollapse 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
- Create
setA, an emptyHashSet<Integer>. It will answer "is this value ina?" quickly. - Loop over
awith a for-each loop and anintnamednum. - Inside the loop, add
numtosetA. Adding a value that is already there changes nothing, so[7, 7, 8]becomes the set{7, 8}. - After the loop, create a second empty set named
common. A set, not a counter, because a value that appears several times inbmust still count once. - Loop over
bthe same way, with anintnamednum. - Inside that loop, if
setA.contains(num)is true, addnumtocommon. The value is then inb, where the loop found it, and ina. - 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:
num | in setA? | common afterwards |
|---|---|---|
| 7 | true | [7] |
| 9 | false | [7] |
| 7 | true | [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
Integerand notint. Java collections hold objects, so a set of numbers is writtenHashSet<Integer>. Java converts betweenintandIntegerautomatically (boxing), which is whysetA.add(num)accepts a plainint. You can't writeHashSet<int>. - The imports.
HashSetlives injava.util. In a standalone program you would start the file withimport java.util.HashSet;orimport java.util.*;. - Set order is not guaranteed. Printing a
HashSetcan 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)boxesnumand compares it withequals, so 7 matches 7 even though they are differentIntegerobjects.
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 anint countand adding 1 for eachbvalue found insetAgives 2 for the second example instead of 1, becausebholds 7 twice. Thecommonset is what prevents it. - Returning
setA.size(). That is the number of different values ina, not the number shared withb. - Negative numbers. Values from -1,000,000,000 to 1,000,000,000 all fit in an
intand work in a set like any other value. - Using
==on boxed values. Comparing twoIntegerobjects with==compares references: with twoIntegervariables that both hold 1000,p == qisfalsewhilep.equals(q)istrue. Let the set'scontainsdo 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.
