Module 18 · Algorithms and Problem Solving — topic 16 of 18
Frequency counting
Solving problems by counting occurrences: counting with dictionaries and Counter, finding the most common and the first unique items, checking anagrams, grouping by signature, and using seen-sets for pair problems.
Learning objectives
- Count frequencies with dict and Counter
- Solve anagram, uniqueness and majority problems
- Replace nested loops with hash-based counting
Definition
Frequency counting records how many times each value occurs, usually in a dictionary or collections.Counter. Many problems become simple, linear-time solutions once frequencies are known.
Introduction
How many times does each word appear? Are these two words anagrams? Which character appears only once? All of these are counting problems.
Why it matters
Counting with a dictionary turns many O(n²) brute-force solutions into O(n) ones, a pattern used constantly in interviews and real data work.
Detailed explanation
The basic pattern: counts[x] = counts.get(x, 0) + 1 for each item.
collections.Counter does this in one step and adds helpers such as most_common(k).
Two strings are anagrams if their character counts are equal, which Counter comparison checks directly.
To find the first unique item, count everything first, then scan the original order for the first item with count 1.
Grouping by a signature — such as the sorted letters of a word — collects related items with a defaultdict(list).
A seen set answers 'have I met this value before?' in O(1), solving duplicate and pair-sum problems in one pass.
Counting costs O(n) time and O(k) space, where k is the number of distinct values.
Normalise data before counting (lower-case, strip punctuation) so 'The' and 'the' are counted together.
Syntax
- Count with dict.get or Counter.
- Compare Counters for anagrams.
- Seen sets for duplicates and pairs.
Code examples
Counting words
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}Most common and first unique
[('s', 3)] wMore examples
Anagrams, groups and pairs
True True False [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']] (5, 7)
Step-by-step explanation
- Comparing Counters checks that both strings use exactly the same letters the same number of times.
- Words with the same sorted letters share a key, so anagrams end up in the same group.
- The seen set finds a pair adding to 12 in one pass instead of checking every pair.
Expected output
Running “Anagrams, groups and pairs” prints exactly:
Practical applications
- Word clouds and log analysis.
- Detecting duplicate transactions or repeated logins.
Best practices
- Use Counter for counting.
- Normalise before counting.
- Reach for a dict or set when you see nested loops comparing items.
Common mistakes
Counting with nested loops
Avoid
Prefer
items.count scans the whole list each time, making the solution quadratic.
Important notes
- Counter supports arithmetic: adding two Counters combines counts.
Key takeaways
- Count with dict.get or Counter.
- Frequencies solve anagram, uniqueness and majority problems.
- Hashing turns O(n²) into O(n).
Try it yourself
- 1Find the element that appears more than half the time in a list, or report none.
- 2Return the k most frequent words in a paragraph, ignoring case and punctuation.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhat is printed?