Problem overview
The function commonCount receives two vectors of integers, a and b. It returns how many different values appear in both. A value counts once, no matter how often it shows up in either vector.
With a = [1, 2, 3, 4] and b = [3, 4, 5] the answer is 2, because 3 and 4 are in both. With a = [7, 7, 8] and b = [7, 9, 7] the answer is 1: 7 appears twice in each vector, but it is one value. With a = [1, 2] and b = [3, 4] nothing is shared, so the answer is 0.
Approach: a set for fast membership, a set for uniqueness
The direct way compares every value of b with every value of a, which takes time proportional to the product of the two sizes. A set removes the inner scan. An unordered_set answers "is this value in here?" in constant time on average, so one pass over b is enough.
Duplicates need care. If b holds 7 twice and 7 is also in a, a plain counter would add 2. The lesson collects the shared values in a second set. Inserting a value that is already in a set changes nothing, so each shared value is stored exactly once, and the size of that set is the answer.
Following the first example: setA holds 1, 2, 3 and 4. The loop reads 3 from b, finds it in setA and inserts it into common. It reads 4 and does the same. It reads 5, which is not in setA, and skips it. common now holds two values, and the function returns 2, the result the example shows.
Step by step
- Put the values of
ain a set namedsetA. The set's constructor accepts a pair of iterators,a.begin()anda.end(), and inserts every value in that range. Repeated values inacollapse into one entry. - Create an empty set named
commonfor the values found in both vectors. - Loop over
bwith a range-basedforand anintnamednum. - Check each value against
setA.setA.count(num)is 1 when the value is present and 0 when it is not, so comparing it with 0 gives a yes or no. On a yes, insertnumintocommon. - Return
common.size()after the loop, once every value ofbhas been checked.
The solution in C++
class Solution {
public:
int commonCount(vector<int>& a, vector<int>& b) {
unordered_set<int> setA(a.begin(), a.end());
unordered_set<int> common;
for (int num : b) {
if (setA.count(num) > 0) {
common.insert(num);
}
}
return common.size();
}
};
A few C++ details:
- Range construction.
unordered_set<int> setA(a.begin(), a.end())builds the set from the vector in one line. Without it you would write a loop ofinsertcalls. counton a set is a membership test. A set stores each value at most once, socountreturns only 0 or 1. Withunordered_set<int> s{1, 2, 3},s.count(2)is 1 ands.count(9)is 0.size()returns an unsigned type. The function's return type isint, so the value is converted on return. That is harmless here, because the count can't exceed the vectors' sizes.- The vectors are passed by reference. The
&invector<int>& aavoids copying the vectors. The function only reads them. - Order is not preserved. An
unordered_setdoesn't remember insertion order. That doesn't matter, since only the count is returned.
Other ways to do it
Two other approaches exist, and both are worth recognising. Sorting both vectors lets you walk them side by side with two indices, advancing the one with the smaller value; that costs O(n log n + m log m) for the sorts and needs care to skip repeated values. The standard library also has set_intersection, which works on sorted ranges. The hash-set version in this lesson is shorter and needs no sorting, so it is the one to reach for first.
Why two sets rather than one
It is tempting to build one set from a and then remove each value from it as it is found in b, counting the removals. That also works, but it changes setA while you are using it for lookups, which makes the logic harder to follow. Keeping setA read-only and collecting results in common keeps each set's role obvious: one answers "is it in a?", the other answers "have I counted it already?".
Complexity
Let the vectors have n and m values. Building setA takes O(n) on average, and the loop over b does O(m) lookups and inserts, each constant time on average. The total is O(n + m) time. The two sets hold at most n and min(n, m) values, so the extra space is O(n + m).
Edge cases and common mistakes
- Counting with an integer instead of a set. Adding 1 for every match gives 2 for
a = [7, 7, 8]andb = [7, 9, 7], where the answer is 1. Storing matches incommonprevents it. - Duplicates in
aonly. They disappear whensetAis built, so they never affect the result. - Extreme values. Values reach a magnitude of one billion, which fits in an
int.[-1000000000, 1000000000]against[1000000000, -1000000000, 0]returns 2. - Same values in a different order.
[1, 2, 3]and[3, 2, 1]return 3. Order plays no role.
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, 5, 5],b = [5]gives 1.a = [1, 2, 3],b = [3, 2, 1]gives 3.
