Length of the longest substring with every character appearing even number of times | C ++ program for the above approach ; Function to find length of the longest substring with each element occurring even number of times ; Initialize unordered_map ; Stores the length of the longest required substring ; Traverse the string ; Stores the value of the digit present at current index ; Bitwise XOR of the mask with 1 left - shifted by val ; Check if the value of mask is already present in ind or not ; Update the final answer ; Otherwise ; Return the answer ; Driver Code ; Given string ; Length of the given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lenOfLongestReqSubstr ( string s , int N ) { unordered_map < int , int > ind ; int mask = 0 ; ind [ 0 ] = -1 ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int val = s [ i ] - '0' ; mask ^= ( 1 << val ) ; if ( ind . find ( mask ) != ind . end ( ) ) { ans = max ( ans , i - ind [ mask ] ) ; } else ind [ mask ] = i ; } return ans ; } int main ( ) { string s = "223015150" ; int N = s . length ( ) ; cout << lenOfLongestReqSubstr ( s , N ) ; return 0 ; }