DEV Community


Posted on

LeetCode 819. Most Common Word (javascript solution)


Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.


Time Complexity : O(n)
Space Complexity: O(n)

var mostCommonWord = function(paragraph, banned) {
  const bannedSet = new Set(banned);
  // Split on each alphanumeric word
  const words = paragraph.toLowerCase().split(/\W+/);
  const map = {};
  for (const w of words) {
    // Count occurrence of each word in words  
    if (!bannedSet.has(w)) {
      if (map[w] == null) map[w] = 0;

  let res = '';
  let max = -Infinity;
  for (const w in map) {
    const count = map[w];
    if (count > max) {
      res = w;
      max = count;
  return res;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)