Longest Common Prefix using Binary Search | 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 ; We will do an in - place binary search on the first string of the array in the range 0 to index ; Same as ( low + high ) / 2 , but avoids overflow for large low and high ; If all the strings in the input array contains this prefix then append this substring to our answer ; And then go for the right part ; Go for the left part ; Driver Code
def findMinLength ( strList ) : NEW_LINE INDENT return len ( min ( arr , key = len ) ) NEW_LINE DEDENT def allContainsPrefix ( strList , str , start , end ) : NEW_LINE INDENT for i in range ( 0 , len ( strList ) ) : NEW_LINE INDENT word = strList [ i ] NEW_LINE for j in range ( start , end + 1 ) : NEW_LINE INDENT if word [ j ] != str [ j ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def CommonPrefix ( strList ) : NEW_LINE INDENT index = findMinLength ( strList ) NEW_LINE low , high = 0 , index - 1 NEW_LINE while low <= high : NEW_LINE INDENT mid = int ( low + ( high - low ) / 2 ) NEW_LINE if allContainsPrefix ( strList , strList [ 0 ] , low , mid ) : NEW_LINE INDENT prefix = prefix + strList [ 0 ] [ low : mid + 1 ] NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return prefix NEW_LINE DEDENT arr = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE lcp = CommonPrefix ( arr ) NEW_LINE if len ( lcp ) > 0 : NEW_LINE INDENT print ( " The ▁ longest ▁ common ▁ prefix ▁ is ▁ " + str ( lcp ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There ▁ is ▁ no ▁ common ▁ prefix " ) NEW_LINE DEDENT