We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Strings
- Making Anagrams
- Discussions
Making Anagrams
Making Anagrams
Sort by
recency
|
757 Discussions
|
Please Login in order to post a comment
Here is my c++ solution, you can watch the explanation here : https://youtu.be/B4pZbX0VzzU
I made an efficient code .Instead of using multiple list comprehensions and sum calls, I streamlined it by reading the lines, processing them, and calculating the differences in one go. This approach minimizes intermediate lists and leverages efficient operations.
import sys from collections import Counter
Read lines from stdin
lines = [sys.stdin.readline().strip() for _ in range(2)]
Count characters in each line
counts = [Counter(line) for line in lines]
Calculate the total difference in counts for each letter
diff = 0 for letter in "abcdefghijklmnopqrstuvwxyz": diff += abs(counts[0].get(letter, 0) - counts[1].get(letter, 0))
print(diff)
for Python3 Platform
I increment the freq for each char from first array and decrement for each char for second array. The common chars therefore will cancel out. The ones that aren't common will either have a positive or negative value. When we add the absolute values we get the total number of different chars. My solution in c / c++. Using either arrays or unordered_map to store the freqeuncy:
//std::unordered_map freq; const int range = 'z' - 'a' + 1; int freq[range] = {0};
Javascript (Typescript)
}