Step 2: Counting the Words Using a HashMap
Why a HashMap?
A HashMap provides an efficient way to store key-value pairs. In our case, the word will be the key, and its frequency will be the value. This will enable us to look up the frequency of a word in constant time.
How to Count?
We'll initialize an empty HashMap (or an object in JavaScript, or a dictionary in Python) to store the occurrences of each word. Let's call this HashMap occurrences
.
Code Snippet for Counting
Here's how you can populate the occurrences
HashMap:
1occurrences := make(map[string]int)
2for _, word := range split_s {
3 _, exists := occurrences[word]
4 if exists {
5 occurrences[word]++
6 } else {
7 occurrences[word] = 1
8 }
9}