LeetCode Solutions

820. Short Encoding of Words

Time: $O(\Sigma \texttt{words[i]})$

Space: $O(\Sigma \texttt{words[i]})$

			

struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  int depth = 0;
  TrieNode() : children(26) {}
};

class Solution {
 public:
  int minimumLengthEncoding(vector<string>& words) {
    int ans = 0;
    shared_ptr<TrieNode> root = make_shared<TrieNode>();
    vector<shared_ptr<TrieNode>> heads;

    for (const string& word : unordered_set<string>(begin(words), end(words)))
      heads.push_back(insert(root, word));

    for (shared_ptr<TrieNode> head : heads)
      if (all_of(begin(head->children), end(head->children),
                 [](const auto& child) { return child == nullptr; }))
        ans += head->depth + 1;

    return ans;
  }

 private:
  shared_ptr<TrieNode> insert(shared_ptr<TrieNode> root, const string& word) {
    shared_ptr<TrieNode> node = root;
    for (const char c : string(rbegin(word), rend(word))) {
      const int i = c - 'a';
      if (node->children[i] == nullptr)
        node->children[i] = make_shared<TrieNode>();
      node = node->children[i];
    }
    node->depth = word.length();
    return node;
  }
};
			

class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public int depth = 0;
}

class Solution {
  public int minimumLengthEncoding(String[] words) {
    int ans = 0;
    TrieNode root = new TrieNode();
    List<TrieNode> heads = new ArrayList<>();

    for (final String word : new HashSet<>(Arrays.asList(words)))
      heads.add(insert(root, word));

    for (TrieNode head : heads)
      if (Arrays.stream(head.children).allMatch(child -> child == null))
        ans += head.depth + 1;

    return ans;
  }

  private TrieNode insert(TrieNode root, final String word) {
    TrieNode node = root;
    for (final char c : new StringBuilder(word).reverse().toString().toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        node.children[i] = new TrieNode();
      node = node.children[i];
    }
    node.depth = word.length();
    return node;
  }
}
			

class TrieNode:
  def __init__(self):
    self.children: Dict[str, TrieNode] = defaultdict(TrieNode)
    self.depth = 0


class Solution:
  def minimumLengthEncoding(self, words: List[str]) -> int:
    root = TrieNode()
    leaves = []

    def insert(word: str) -> TrieNode:
      node = root
      for c in reversed(word):
        if c not in node.children:
          node.children[c] = TrieNode()
        node = node.children[c]
      node.depth = len(word)
      return node

    for word in set(words):
      leaves.append(insert(word))

    return sum(leaf.depth + 1 for leaf in leaves
               if not len(leaf.children))