See the original problem on HackerRank.
Solutions
Two strings are anagrams of one another if they share the same characters and each character has the same frequency in both strings. Thus, we can easily solve this problem with a frequency table.
Basically, we can add 1
for each character in a
and subtract 1
for each character in b
. Those characters with nonzero frequency must be deleted and then added to the total count.
Here is an implementation in C++:


The reduce pattern brings out thus the third for loop can be replaced with:


Just for fun, here is a possible implementation of the same call to accumulate
with C++20 ranges:


An alternative solution consists in using a set operation to calculate the symmetric difference between the two strings: the symmetric difference between two sets is the set of all those elements which belongs either to the first one or to the second one but not to both.
It’s important to take into accounts multiple occurrences of elements. In C++ we can use set_symmetric_difference
because it does it by design:


(the additional storage is not really needed: we might create a fake output iterator which just increment a counter).
An alternative approach, using a 2pointer technique, has been developed by Andrea Battistello and Lucio Grenzi:


Actually, this idea is more or less the same as calculating the symmetric difference between two sets.