Skip to content

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.

Beginner 10 min read·Lesson 276 of 306 in Python Programming

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

Python
from collections import Counter
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
Counter(words).most_common(3)
  • Count with dict.get or Counter.
  • Compare Counters for anagrams.
  • Seen sets for duplicates and pairs.

Code examples

Counting words

Python
text = "the cat and the hat and the bat"
counts = {}
for w in text.split():
counts[w] = counts.get(w, 0) + 1
print(counts)
Output
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}

Most common and first unique

Python
from collections import Counter
s = "swiss"
c = Counter(s)
print(c.most_common(1), next((ch for ch in s if c[ch] == 1), None))
Output
[('s', 3)] w

More examples

Anagrams, groups and pairs

Python
from collections import Counter, defaultdict
def are_anagrams(a, b):
return Counter(a.replace(" ", "").lower()) == Counter(b.replace(" ", "").lower())
print(are_anagrams("Listen", "Silent"), are_anagrams("Dormitory", "Dirty room"), are_anagrams("abc", "abd"))
groups = defaultdict(list)
for w in ["eat", "tea", "tan", "ate", "nat", "bat"]:
groups["".join(sorted(w))].append(w)
print(list(groups.values()))
def pair_with_sum(nums, target):
seen = set()
for n in nums:
if target - n in seen:
return (target - n, n)
seen.add(n)
return None
print(pair_with_sum([8, 3, 11, 5, 7], 12))
Output
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:

TextOutput
True True False
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
(5, 7)

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

for x in items:
count = items.count(x) # O(n) inside O(n)

Prefer

counts = Counter(items)

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

  1. 1
    Find the element that appears more than half the time in a list, or report none.
  2. 2
    Return 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?
Practise this topic