LeetCode Solutions

720. Longest Word in Dictionary

Time:

Space:

			

struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  const string* word = nullptr;
  TrieNode() : children(26) {}
};

class Solution {
 public:
  string longestWord(vector<string>& words) {
    for (const string& word : words)
      insert(word);
    return longestWordFrom(root);
  }

 private:
  shared_ptr<TrieNode> root = make_shared<TrieNode>();

  void insert(const string& word) {
    shared_ptr<TrieNode> node = root;
    for (const char c : word) {
      const int i = c - 'a';
      if (node->children[i] == nullptr)
        node->children[i] = make_shared<TrieNode>();
      node = node->children[i];
    }
    node->word = &word;
  }

  string longestWordFrom(shared_ptr<TrieNode> node) {
    string ans = node->word ? *node->word : "";

    for (shared_ptr<TrieNode> child : node->children)
      if (child && child->word) {
        string childWord = longestWordFrom(child);
        if (childWord.length() > ans.length())
          ans = childWord;
      }

    return ans;
  }
};
			

class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public String word;
}

class Solution {
  public String longestWord(String[] words) {
    for (final String word : words)
      insert(word);
    return longestWordFrom(root);
  }

  private TrieNode root = new TrieNode();

  private void insert(final String word) {
    TrieNode node = root;
    for (char c : word.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        node.children[i] = new TrieNode();
      node = node.children[i];
    }
    node.word = word;
  }

  private String longestWordFrom(TrieNode node) {
    String ans = node.word == null ? "" : node.word;

    for (TrieNode child : node.children)
      if (child != null && child.word != null) {
        String childWord = longestWordFrom(child);
        if (childWord.length() > ans.length())
          ans = childWord;
      }

    return ans;
  }
}
			

class Solution:
  def longestWord(self, words: List[str]) -> str:
    root = {}

    for word in words:
      node = root
      for c in word:
        if c not in node:
          node[c] = {}
        node = node[c]
      node['word'] = word

    def dfs(node: dict) -> str:
      ans = node['word'] if 'word' in node else ''

      for child in node:
        if 'word' in node[child] and len(node[child]['word']) > 0:
          childWord = dfs(node[child])
          if len(childWord) > len(ans) or (len(childWord) == len(ans) and childWord < ans):
            ans = childWord

      return ans

    return dfs(root)