Sum of Prefix Scores of Strings - Trie [JS]

Description 

Solution: Trie

Store each word in a trie.
For every node in the trie, keep track of the number of words it is part of.

Since we stored the count of words on every node, we can calculate the count of every prefix for every word on the fly.

n = number of wordsm = max(words[i].length)
Time Complexity: O(nm)
Space Complexity: O(26^m) at worst

var sumPrefixScores = function(words) {
  let trie = new Trie();
  for (let word of words) {
    trie.add(word);
  } 

  let n = words.length, res = Array(n);
  for (let i = 0; i < words.length; i++) {
    res[i] = trie.getScore(words[i]);
  }
  return res;
};

class TrieNode {
  constructor() {
    this.children = {};
    this.count = 0; 
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }
  add(word) {
    let node = this.root;
    for (let i = 0; i < word.length; i++) {
      node = node.children;
      let char = word[i];
      if (!node[char]) node[char] = new TrieNode();
      node = node[char];
      node.count++;
    }
  }
  getScore(word) {
    let node = this.root, score = 0;
    for (let i = 0; i < word.length; i++) {
      node = node.children;
      let char = word[i];
      if (!node[char]) return score;
      node = node[char];
      score += node.count;
    }
    return score;
  }
}

Comments

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]