Pair of strings having longest common prefix of maximum length in given array | Class of Trie ; Function to insert a string into Trie ; Stores length of the string ; Traverse the string str ; If str [ i ] is not present in current path of Trie ; Create a new node of Trie ; Update root ; Function to find the maximum length of longest common prefix in Trie with str ; Stores length of str ; Stores length of longest common prefix in Trie with str ; Traverse the string str ; If str [ i ] is present in the current path of Trie ; Update len ; Update root ; Function to print the pair having maximum length of the longest common prefix ; Stores index of the string having maximum length of longest common prefix ; Stores maximum length of longest common prefix . ; Create root node of Trie ; Insert arr [ 0 ] into Trie ; Traverse the array . ; Stores maximum length of longest common prefix in Trie with arr [ i ] ; If temp is greater than len ; Update len ; Update idx ; Traverse array arr [ ] ; Stores length of arr [ i ] ; Check if maximum length of longest common prefix > M ; Traverse string arr [ i ] and arr [ j ] ; If current character of both string does not match . ; Print pairs having maximum length of the longest common prefix ; Driver Code
class TrieNode { constructor ( ) { this . child = Array ( 256 ) ; } } ; function insertTrie ( root , str ) { var M = str . length ; for ( var i = 0 ; i < M ; i ++ ) { if ( root . child [ str [ i ] ] == null ) { root . child [ str [ i ] ] = new TrieNode ( ) ; } root = root . child [ str [ i ] ] ; } } function findStrLen ( root , str ) { var M = str . length ; var len = 0 ; for ( var i = 0 ; i < M ; i ++ ) { if ( root . child [ str [ i ] ] != null ) { len ++ ; root = root . child [ str [ i ] ] ; } else { return len ; } } return len ; } function findMaxLenPair ( arr , N ) { var idx = - 1 ; var len = 0 ; var root = new TrieNode ( ) ; insertTrie ( root , arr [ 0 ] ) ; for ( var i = 1 ; i < N ; i ++ ) { var temp = findStrLen ( root , arr [ i ] ) ; if ( temp > len ) { len = temp ; idx = i ; } insertTrie ( root , arr [ i ] ) ; } for ( var i = 0 ; i < N ; i ++ ) { var M = arr [ i ] . length ; if ( i != idx && M >= len ) { var found = true ; for ( var j = 0 ; j < len ; j ++ ) { if ( arr [ i ] [ j ] != arr [ idx ] [ j ] ) { found = false ; break ; } } if ( found ) { document . write ( " " + arr [ i ] + " " + arr [ idx ] + " " ) ; return ; } } } } var arr = [ " " , " " , " " ] ; var N = arr . length ; findMaxLenPair ( arr , N ) ;