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.

Counting the Words Using a HashMap

Code Snippet for Counting

Here's how you can populate the occurrences HashMap:

1occurrences = {}
2for word in split_s:
3    if word in occurrences:
4        occurrences[word] += 1
5    else:
6        occurrences[word] = 1