Many problems secretly ask the same question: how many times did each thing appear? A frequency table stores that answer while you scan the data once.
The item becomes a key
For each item, look up its current count and add one. A dictionary is a good fit because it connects each item to its count.
- Find duplicates in a list.
- Discover the most common word.
- Check whether two words use the same letters.
- Group equal values before processing them.
One pass builds the table
def frequencies(colors):
counts = {}
for color in colors:
counts[color] = counts.get(color, 0) + 1
return counts
print(frequencies(["blue", "red", "blue"]))
# {'blue': 2, 'red': 1}This usually takes O(n) time because each item is visited once. The table uses extra memory, but it can replace much slower repeated searching.
The useful clue is repetition. If a prompt asks about counts, duplicates, pairs, or matching collections, consider a frequency table.
Your tiny challenge
Count the letters in banana. Then use the table to say which letter appears most often.
