Approach: The solution splits the input string into individual words using whitespace as the delimiter. A HashMap is then used to store each word as the key and its occurrence count as the value. If a word already exists in the map, its count is incremented; otherwise, it is added with an initial count of 1.
HashMap provides constant-time average lookup and update operations, making it an efficient choice for frequency counting problems.
Java Solution:
import java.util.HashMap;
import java.util.Map;
public class WordCountUsingHashMap {
public static void main(String[] args) {
String input = "Java is powerful and Java is popular";
String[] words = input.split("\\s+");
Map<String, Integer> wordCountMap = new HashMap<>();
for (String word : words) {
wordCountMap.put(
word,wordCountMap.getOrDefault(word, 0) + 1
);
}
for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}Output: Java : 2 is : 2 powerful : 1 and : 1 popular : 1
Time Complexity: O(n), where n is the number of words in the input string. Each word is processed exactly once.
Space Complexity: O(k), where k is the number of unique words stored in the HashMap.
Key Interview Points: • HashMap is commonly used for frequency counting problems because of its O(1) average lookup and insertion time. • The getOrDefault() method simplifies the logic for handling existing and new words. • A common follow-up question is to find the first non-repeated word or the most frequently occurring word in the string.