#4 Finding the Most Frequent String
 in an Array

#4 Finding the Most Frequent String in an Array

Introduction:

In this blog post, we will explore a Java code snippet that efficiently finds the most frequent element in an array using a hash map. We will provide a clear example, explain the code step by step, and conclude with the benefits of this approach.

Example:

Suppose we have an array of strings: {"hi", "hey", "hi", "hi", "hello", "hey"}. Our goal is to determine which string occurs most frequently in the array: "hi"

Explanation:

Let's break down the code step by step:

  1. We start by initializing our input array of strings.

String[] inputStr = {"hi", "hey", "hi", "hi", "hello", "hey"};        

2. We create a hash map to store the frequency of each string.

Map<String, Integer> frequencyMap = new HashMap<>();        

3. We iterate through each string in the input array. For each string, we check if it already exists in the hash map. If it does, we increment its frequency by 1; if not, we add it to the hash map with a frequency of 1.

for (String str : inputStr) {
    if(frequencyMap.containsKey(str)){
        frequencyMap.put(str, frequencyMap.get(str) + 1);
    } else {
        frequencyMap.put(str, 1);
    }
}        

4. Next, we iterate through the entries in the frequency map to find the string with the highest frequency. We keep track of the maximum count and the corresponding string.

int maxCount = -1
String maxStr = "";


for(Map.Entry<String, Integer> entry : frequencyMap.entrySet()){
    if(entry.getValue() > maxCount){
        maxCount = entry.getValue();
        maxStr = entry.getKey();
    }
}        

5. Finally, we print the most frequent string.

System.out.println(maxStr);         

Complete Code:

public static void main(String[] args) {
    // Input array of strings
    String[] inputStr = {"hi", "hey", "hi", "hi", "hello", "hey"};


    // Create a frequency map to count occurrences of each string
    Map<String, Integer> frequencyMap = new HashMap<>();
    for (String str : inputStr) {
        // Check if the string is already in the map
        if (frequencyMap.containsKey(str)) {
            // Increment the count for the existing string
            frequencyMap.put(str, frequencyMap.get(str) + 1);
        } else {
            // Add the new string to the map with count 1
            frequencyMap.put(str, 1);
        }
    }


    // Find the most frequent string and its count
    int maxCount = -1;
    String maxStr = "";
    for (Map.Entry<String, Integer> entry : frequencyMap.entrySet()) {
        // Compare the current count with the maxCount
        if (entry.getValue() > maxCount) {
            maxCount = entry.getValue();
            maxStr = entry.getKey();
        }
    }


    // Print the most frequent string
    System.out.println("Most frequent string: " + maxStr + " (Count: " + maxCount + ")");
}
        

Conclusion:

The provided Java code snippet efficiently solves the problem of finding the most frequent element in an array using a hash map. This approach avoids the need for nested loops and has a time complexity of O(n), where n is the number of elements in the input array. By utilizing a hash map to store and update the frequency of each element, the code ensures a faster and more scalable solution compared to other methods.


To view or add a comment, sign in

More articles by RUPA SHREE K

Explore content categories