It is a google interview question and I find most answers online using HashMap or similar data structure. I am trying to find a solution using Trie if possible. Anybody could gi
I suspect a Trie-based implementation wouldn't be very space-efficient, but it would parallelize very nicely, because you could descend into all branches of the tree in parallel and collected the deepest nodes which you can reach from each top branch with the given set of letters. In the end, you just collect all the deepest nodes and select the longest one.
I'd start with this algorithm (sorry, just pseudo-code), which doesn't attempt to parallelize but just uses plain old recursion (and backtracking) to find the longest match:
TrieNode visitNode( TrieNode n, LetterCollection c )
{
TreeNode deepestNode = n;
for each Letter l in c:
TrieNode childNode = n.getChildFor( l );
if childNode:
TreeNode deepestSubNode = visitNode( childNode, c.without( l ) );
if deepestSubNode.stringLength > deepestNode.stringLength:
deepestNode = deepestSubNode;
return deepestNode;
}
I.e. this function is supposed to start at the root node of the trie, with the entire given letter collection. For each letter in the collection, you try to find a child node. If there is one, you recurse and remove the letter from the collection. At one point your letter collection will be empty (best case, all letters consumes - you could actually bail out right away without continueing to traverse the trie) or there will be no more children with any of the remaining letters - in that case you remove the node itself, because that's your "longest match".
This could parallelize quite nicely if you changed the recursion step so that you visit all children in parallel, collect the results - and select the longest result and return that.