Longest Common Prefix Matching | Set | A Utility Function to find the common prefix between first and last strings ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; sorts the N set of strings ; prints the common prefix of the first and the last string of the set of strings ; Driver Code
def commonPrefixUtil ( str1 , str2 ) : NEW_LINE INDENT n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE result = " " NEW_LINE j = 0 NEW_LINE i = 0 NEW_LINE while ( i <= n1 - 1 and j <= n2 - 1 ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT result += ( str1 [ i ] ) NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return ( result ) NEW_LINE DEDENT def commonPrefix ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE print ( commonPrefixUtil ( arr [ 0 ] , arr [ n - 1 ] ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE n = len ( arr ) NEW_LINE commonPrefix ( arr , n ) NEW_LINE DEDENT