Longest Common Prefix using Sorting | Javascript program to find longest common prefix of given array of words . ; if size is 0 , return empty string ; sort the array of strings ; find the minimum length from first and last string ; find the common prefix between the first and last string ; Driver Function to test other function
function longestCommonPrefix ( a ) { let size = a . length ; if ( size == 0 ) return " " ; if ( size == 1 ) return a [ 0 ] ; a . sort ( ) ; let end = Math . min ( a [ 0 ] . length , a [ size - 1 ] . length ) ; let i = 0 ; while ( i < end && a [ 0 ] [ i ] == a [ size - 1 ] [ i ] ) i ++ ; let pre = a [ 0 ] . substring ( 0 , i ) ; return pre ; } let input = [ " " , " " , " " , " " ] ; document . write ( " " + longestCommonPrefix ( input ) ) ;