Count how many times each element appears in a collection. Build a frequency map in one pass, then query counts or compare distributions. Uses a dictionary under the hood.
def count_frequencies(s):
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
return freq
# Or use Counter from collections
from collections import Counter
freq = Counter(s) # same result, one line
unordered_map<char,int> countFrequencies(string s) {
unordered_map<char,int> freq;
for (char ch : s) {
freq[ch]++; // auto-initializes to 0
}
return freq;
}
Dictionary<char,int> CountFrequencies(string s) {
var freq = new Dictionary<char,int>();
foreach (char ch in s) {
freq[ch] = freq.GetValueOrDefault(ch, 0) + 1;
}
return freq;
}
Map<Character,Integer> countFrequencies(String s) {
Map<Character,Integer> freq = new HashMap<>();
for (char ch : s.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
return freq;
}
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
return Counter(s1) == Counter(s2) # compare frequency maps
bool isAnagram(string s1, string s2) {
if (s1.size() != s2.size()) return false;
unordered_map<char,int> freq;
for (char ch : s1) freq[ch]++;
for (char ch : s2) {
if (--freq[ch] < 0) return false;
}
return true;
}
bool IsAnagram(string s1, string s2) {
if (s1.Length != s2.Length) return false;
var freq = new Dictionary<char,int>();
foreach (char ch in s1)
freq[ch] = freq.GetValueOrDefault(ch, 0) + 1;
foreach (char ch in s2) {
if (!freq.ContainsKey(ch) || --freq[ch] < 0)
return false;
}
return true;
}
boolean isAnagram(String s1, String s2) {
if (s1.length() != s2.length()) return false;
Map<Character,Integer> freq = new HashMap<>();
for (char ch : s1.toCharArray())
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
for (char ch : s2.toCharArray()) {
int count = freq.getOrDefault(ch, 0) - 1;
if (count < 0) return false;
freq.put(ch, count);
}
return true;
}
def most_frequent(s):
freq = Counter(s)
return freq.most_common(1)[0] # returns (element, count)
pair<char,int> mostFrequent(string s) {
unordered_map<char,int> freq;
for (char ch : s) freq[ch]++;
pair<char,int> best = {'\0', 0};
for (auto& [ch, cnt] : freq)
if (cnt > best.second) best = {ch, cnt};
return best;
}
(char, int) MostFrequent(string s) {
var freq = new Dictionary<char,int>();
foreach (char ch in s)
freq[ch] = freq.GetValueOrDefault(ch, 0) + 1;
return freq.OrderByDescending(x => x.Value).First()
.Let(x => (x.Key, x.Value));
}
Map.Entry<Character,Integer> mostFrequent(String s) {
Map<Character,Integer> freq = new HashMap<>();
for (char ch : s.toCharArray())
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
return Collections.max(freq.entrySet(),
Map.Entry.comparingByValue());
}