Hash maps and counting
Count values in one pass by storing a lookup table of items already seen.
Choose a unique key
A hash map associates one value with each key. For a frequency table, use the input item as the key and the number of occurrences as the value. When an item appears again, update its existing count.
How it works
For each value, look up its current count. Use zero when the key has not appeared, then add one and store the result. On a, b, a, the counts become a=1, then b=1, then a=2. A single scan handles repeated items without recounting the whole input.
Describe the complexity
With expected constant-time lookup and update, a single scan builds the counts in expected O(n) time. A map containing k distinct keys takes O(k) space. Counting each different item with its own full scan can take O(n²) work when all items differ.
Code example
labels = ["red", "blue", "red"]
counts = {}
for label in labels:
counts[label] = counts.get(label, 0) + 1
print(counts.get("red", 0))Check your understanding
Return the first label seen a second time, or "None" if all labels are unique.
See the example and explanation
- Example 1
- Given
["A", "B", "B", "A"] - Answer
B - Example 2
- Given
["A", "B", "C"] - Answer
None
Process labels from left to right. If the current label is already present, return it immediately. Otherwise add it and keep scanning.