Longest Common Prefix using Sorting | Python 3 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 Code
def longestCommonPrefix ( a ) : NEW_LINE INDENT size = len ( a ) NEW_LINE if ( size == 0 ) : NEW_LINE INDENT return " " NEW_LINE DEDENT if ( size == 1 ) : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT a . sort ( ) NEW_LINE end = min ( len ( a [ 0 ] ) , len ( a [ size - 1 ] ) ) NEW_LINE i = 0 NEW_LINE while ( i < end and a [ 0 ] [ i ] == a [ size - 1 ] [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT pre = a [ 0 ] [ 0 : i ] NEW_LINE return pre NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE print ( " The ▁ longest ▁ Common ▁ Prefix ▁ is ▁ : " , longestCommonPrefix ( input ) ) NEW_LINE DEDENT