Key Takeaways: The terms "Hash Table" and "Hash Map" are often used interchangeably. While a Hash Table refers to the underlying data structure, a Hash Map emphasizes the relationship of mapping a unique Key to a specific Value.
You already know how Hash Tables work under the hood from our previous tutorials.
Now, let's look at one of the most common and powerful ways Software Engineers actually use Hash Maps in the real world: Frequency Counting.
A very common task in programming is taking a massive list of items and counting how many times each item appears.
If you try to solve this using only Arrays, you will have to use nested loops. This creates an O(n²) Time Complexity, which is extremely slow.
Instead, we can use a Hash Map!
Imagine we have an array of fruits: ["Apple", "Banana", "Apple", "Cherry", "Apple"]
We will create an empty Hash Map: {}
"Apple". Is it in the map? No. Add it with a value of 1. Map: {"Apple": 1}."Banana". Is it in the map? No. Add it with a value of 1. Map: {"Apple": 1, "Banana": 1}."Apple". Is it in the map? Yes! Update its value by +1. Map: {"Apple": 2, "Banana": 1}."Cherry". Is it in the map? No. Add it with a value of 1. Map: {"Apple": 2, "Banana": 1, "Cherry": 1}."Apple". Is it in the map? Yes! Update its value by +1. Map: {"Apple": 3, "Banana": 1, "Cherry": 1}.Hash Map: Condensing a large array into clean Key-Value pairs.
Because checking if a Key exists in a Hash Map takes O(1) constant time!
We only had to loop through our array exactly once. This means our Time Complexity is just O(n) linear time.
If our array had 1,000,000 fruits, the Hash Map would finish counting them almost instantly, whereas an Array-only approach might take several minutes to run!
Let's write out this Frequency Counter pattern in Python using a Dictionary (which is Python's version of a Hash Map).
def count_frequencies(items): # 1. Create an empty Hash Map (Dictionary) frequency_map = {} # 2. Loop through the array once for item in items: # If the item is already a Key in the map, increase its Value if item in frequency_map: frequency_map[item] += 1 # If it's not in the map, add it with a Value of 1 else: frequency_map[item] = 1 return frequency_mapfruits = ["Apple", "Banana", "Apple", "Cherry", "Apple"]
print("Raw Array:", fruits) print("Hash Map Result:", count_frequencies(fruits))
In a Frequency Counter Hash Map, what do the Keys and Values typically represent?
What is the Time Complexity of building a frequency map from an array of n items?