A solution using PriorityQueue. It’s still O(n) as heapify is used:
public static String mostCommonWord(String paragraph, List<String> banned) {
Queue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a, b) -> {
return -a.getValue().compareTo(b.getValue());
});
Map<String, Integer> hm = new HashMap<>();
String[] paragraphArray = paragraph.replaceAll("[^a-zA-Z ]", "").toLowerCase().split(" ");
for (String word : paragraphArray) {
if (!banned.contains(word)) {
if (hm.containsKey(word)) {
hm.put(word, hm.get(word) + 1);
} else {
hm.put(word, 1);
}
}
}
pq.addAll(hm.entrySet());
Map.Entry<String, Integer> mostUsedWordEntry = pq.poll();
return mostUsedWordEntry.getKey();
}