Maximum number of characters between any two same character in a string | Efficient Python3 program to find maximum number of characters between two occurrences of same character ; Initialize all indexes as - 1. ; If this is first occurrence ; Else find distance from previous occurrence and update result ( if required ) . ; Driver code
MAX_CHAR = 256 NEW_LINE def maximumChars ( str1 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE res = - 1 NEW_LINE firstInd = [ - 1 for i in range ( MAX_CHAR ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT first_ind = firstInd [ ord ( str1 [ i ] ) ] NEW_LINE if ( first_ind == - 1 ) : NEW_LINE INDENT firstInd [ ord ( str1 [ i ] ) ] = i NEW_LINE DEDENT else : NEW_LINE INDENT res = max ( res , abs ( i - first_ind - 1 ) ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT str1 = " abba " NEW_LINE print ( maximumChars ( str1 ) ) NEW_LINE