problemeasyalgorithms

Find frequency of a word in a book

EasyUpdated: Aug 2, 2025

Problem

Design a method to find the frequency of occurrences of any given word in a book.

Examples

Example 1:

Input:
BookFrequency(String text)

text = 
the day is sunny the the
the sunny is is

Input:
getFrequency("the")
Output: 4

Input:
getFrequency("is")
Output: 3

Here is similar problem with bash script: [Word Frequency from File](word-frequency-from-file).

Solution

Method 1 - Using Hashmap

Just scan the word, trim it and put in HashMap. Now, when searching lower case it and search it.

Code

Java
class Book {
	private Map<String, Integer> map;
	public Book(String[] book) {
		map = new HashMap<>();
		for (String word: book) {
			word = word.toLowerCase();

			if (word.trim() != "") {
				map.put(word, map.getOrDefault(word, 0) + 1);	
			}
	}


	public getFrequency(String word) {
		word = word.toLowerCase();
		return map.getOrDefault(word, 0);
	}
}

Comments