Find the duplicate characters in a string in O ( 1 ) space | Function to find duplicate characters in string without using any additional data structure ; Check if ( i + ' a ' ) is present in str at least once or not . ; Check if ( i + ' a ' ) is present in str at least twice or not . ; Iterate over the characters of the string str ; If str [ i ] has already occurred in str ; Set ( str [ i ] - ' a ' ) - th bit of second ; Set ( str [ i ] - ' a ' ) - th bit of second ; Iterate over the range [ 0 , 25 ] ; If i - th bit of both first and second is Set ; Driver code
function findDuplicate ( str , N ) { let first = 0 ; let second = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( ( first & ( 1 << ( str [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) ) ) != 0 ) { second = second | ( 1 << ( str [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) ) ; } else { first = first | ( 1 << ( str [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) ) ; } } for ( let i = 0 ; i < 26 ; i ++ ) { if ( ( ( first & ( 1 << i ) ) & ( second & ( 1 << i ) ) ) != 0 ) { document . write ( String . fromCharCode ( i + ' ' . charCodeAt ( ) ) + " " ) ; } } } let str = " " ; let N = str . length ; findDuplicate ( str , N ) ;