Longest Common Prefix using Character by Character Matching | A Function to find the string having the minimum length and returns that length ; A Function that returns the longest common prefix from the array of strings ; Our resultant string let current ; The current character ; Current character ( must be same in all strings to be a part of result ) ; Append to result ; Driver program to test above function
function findMinLength ( arr , n ) { let min = arr [ 0 ] . length ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] . length < min ) { min = arr [ i ] . length ; } } return ( min ) ; } function commonPrefix ( arr , n ) { let minlen = findMinLength ( arr , n ) ; let result = " " ; for ( let i = 0 ; i < minlen ; i ++ ) { current = arr [ 0 ] [ i ] ; for ( let j = 1 ; j < n ; j ++ ) { if ( arr [ j ] [ i ] != current ) { return result ; } } result += ( current ) ; } return ( result ) ; } let arr = [ " " , " " , " " , " " ] let n = arr . length ; let ans = commonPrefix ( arr , n ) ; if ( ans . length > 0 ) { document . write ( " " + ans ) ; } else { document . write ( " " ) ; }