Salesforce | Phone Interview | Most Frequent N-Gram
Anonymous User
2040

Write a function that takes a string of characters and an integer n and returns the most frequent n-gram.

Example: for ‘abcdabxexexe’ and 2 returns ‘xe’.

This is the solution I came up with but feel like there's a more efficient way of doing it rather than calling substring each time which takes O(n). Any thoughts?

public String mostCommonNGram(String word, int n) {
    Map<String, Integer> nGramCount = new HashMap<>();
    for (int i = 0; i <= word.length() - n; i++) {
	    String currGram = word.substring(i, i+n); // Potentially more efficient way?
	    nGramCount.put(currGram, nGramCount.getOrDefault(currGram, 0) + 1); 
	}
	    
    int max = 0;
	String ans = "";
	for (Map.Entry<String, Integer> entry : nGramCount.entrySet()) {
	    if (entry.getValue() > max) { 
	        max = entry.getValue();
	        ans = entry.getKey();
	    }
	}
	    
	return ans;
}
Comments (4)