Longest substring whose characters can be rearranged to form a Palindrome | Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through each character of the string ; Convert the character from [ a , z ] to [ 0 , 25 ] ; Turn the temp - th bit on if character occurs odd number of times and turn off the temp - th bit off if the character occurs ever number of times ; If a mask is present in the index Therefore a palindrome is found from index [ mask ] to i ; If x is not found then add its position in the index dict . ; Check for the palindrome of odd length ; We cancel the occurrence of a character if it occurs odd number times ; Given String ; Length of given string ; Function call
def longestSubstring ( s : str , n : int ) : NEW_LINE INDENT index = dict ( ) NEW_LINE answer = 0 NEW_LINE mask = 0 NEW_LINE index [ mask ] = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = ord ( s [ i ] ) - 97 NEW_LINE mask ^= ( 1 << temp ) NEW_LINE if mask in index . keys ( ) : NEW_LINE INDENT answer = max ( answer , i - index [ mask ] ) NEW_LINE DEDENT else : NEW_LINE INDENT index [ mask ] = i NEW_LINE DEDENT for j in range ( 26 ) : NEW_LINE INDENT mask2 = mask ^ ( 1 << j ) NEW_LINE if mask2 in index . keys ( ) : NEW_LINE INDENT answer = max ( answer , i - index [ mask2 ] ) NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT s = " adbabd " NEW_LINE n = len ( s ) NEW_LINE print ( longestSubstring ( s , n ) ) NEW_LINE