Leetcode

Short Encoding of Words

Approach 1: Trie

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

C++

struct TrieNode {
  vector<TrieNode*> children;
  int depth = 0;
  TrieNode() : children(26) {}
  ~TrieNode() {
    for (TrieNode* child : children)
      delete child;
  }
};

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

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

    for (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:
  TrieNode* insert(TrieNode* root, const string& word) {
    TrieNode* node = root;
    for (const char c : string(rbegin(word), rend(word))) {
      if (!node->children[c - 'a'])
        node->children[c - 'a'] = new TrieNode;
      node = node->children[c - 'a'];
    }
    node->depth = word.length();
    return node;
  }
};

JAVA

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()) {
      if (node.children[c - 'a'] == null)
        node.children[c - 'a'] = new TrieNode();
      node = node.children[c - 'a'];
    }
    node.depth = word.length();
    return node;
  }
}

Python

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))

Approach 2: C++ string_view

  • Time:O(|\texttt{words}| \cdot |\texttt{words[i]}|^2)
  • Space:O(|\texttt{words}| \cdot |\texttt{words[i]}|)

C++

class Solution {
 public:
  int minimumLengthEncoding(vector<string>& words) {
    unordered_set<string_view> wordsSet(begin(words), end(words));

    for (const auto& word : words) {
      const string_view sv(word);
      for (int i = 1; i < word.length(); ++i)
        wordsSet.erase(sv.substr(i));
    }

    return accumulate(
        begin(wordsSet), end(wordsSet), 0,
        [](int accu, const auto& sv) { return accu + sv.length() + 1; });
  }
};