Trie DFS through word nodes
Time O(total characters) Space O(total characters)Insert all words storing each at its end node. DFS from the root visiting children a to z, but only into nodes that hold a word. Track the longest word found.
class Solution {
private static class Node {
Node[] next = new Node[26];
String word;
}
private String best = "";
public String longestWord(String[] words) {
Node root = new Node();
for (String w : words) {
Node n = root;
for (char c : w.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
n = n.next[c - 'a'];
}
n.word = w;
}
dfs(root);
return best;
}
private void dfs(Node n) {
for (Node child : n.next) {
if (child == null || child.word == null) continue;
if (child.word.length() > best.length()) best = child.word;
dfs(child);
}
}
}Verdict: Alphabetical DFS handles the tie-break for free.