Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.

If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.

Note that the word should be built from left to right with each additional character being added to the end of a previous word.&nbsp;

&nbsp;
Example 1:

Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".


Example 2:

Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".


&nbsp;
Constraints:


	1 &lt;= words.length &lt;= 1000
	1 &lt;= words[i].length &lt;= 30
	words[i] consists of lowercase English letters.


class Solution:
    def longestWord(self, words: List[str]) -> str:
        TrieNode = lambda: defaultdict(TrieNode)
        root = TrieNode()
        for i,s in enumerate(words):
            cur = root
            for c in s: cur=cur[c]
            cur['$']=i

        ans = ''
        st = list(root.values())
        while st:
            cur = st.pop()
            if '$' in cur:
                w = words[cur['$']]
                if len(ans)<len(w) or len(ans)==len(w) and w<ans:ans=w
                st.extend([cur[i] for i in cur if i!='$'])
        return ans
class Solution {
    private class Node{
        Node[] sub;
        Node(){
            sub = new Node[26];
        }
    }
    Node root;
    StringBuilder ans;
    private void buildTire(String word){
        Node temp = root;
        int n = word.length();
        for(int i = 0; i < n-1; i++){
            int index = word.charAt(i)-'a';
            if(temp.sub[index] == null) return;
            temp = temp.sub[index];
        }
        int index = word.charAt(n-1)-'a';
        temp.sub[index] = new Node();
        
        if(word.length() > ans.length())
            ans = new StringBuilder(word);
    }
    public String longestWord(String[] words) {
        this.ans = new StringBuilder();
        this.root = new Node();
        PriorityQueue<String> pq = new PriorityQueue<>();
        pq.addAll(Arrays.asList(words));
        while(!pq.isEmpty()) buildTire(pq.poll());
        return ans.toString();
    }
}
struct node{
    int end=0;
    node* adj[26];
};

class Solution {
public:
    string longestWord(vector<string>& words) {
        auto root = new node();
        auto insert = [&](string&s, int ind){
            node* cur = root;
            int i;
            for(char&c:s){
                i=c - 'a';
                if(!cur->adj[i])cur->adj[i] = new node();
                cur=cur->adj[i];
            }
            cur->end=ind;
        };

        int ind = 0;
        for(string&s : words) insert(s,++ind);

        stack<node*> st;
        st.push(root);
        string ans = "";
        while(!st.empty()){
            node* cur = st.top();st.pop();
            if(cur->end>0 || cur==root){
                if(cur!=root){
                    string word = words[cur->end-1];
                    if(word.size()>ans.size() ||
                      (word.size()==ans.size() && word<ans)){ans = word;}
                }

                for(int j=0;j<26;j++)
                    if(cur->adj[j])st.push(cur->adj[j]);
            }
        }
        return ans;
    }
};
var longestWord = function(words) {
  words.sort();
  let trie = new Trie();
  let result = ""
  
  for (const word of words) {
      if (word.length === 1) {
          trie.insert(word);
          result = word.length > result.length ? word : result;
      } else {
          let has = trie.search(word.slice(0, word.length-1));
          if (has) {
              trie.insert(word);
              result = word.length > result.length ? word : result;
          }
      }
  }
  
  return result;
};
Longest Word in Dictionary