Find the duplicate characters in a string in O ( 1 ) space | Java program for the above approach ; 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
public class GFG { static void findDuplicate ( String str , int N ) { int first = 0 ; int second = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( first & ( 1 << ( str . charAt ( i ) - ' a ' ) ) ) != 0 ) { second = second | ( 1 << ( str . charAt ( i ) - ' a ' ) ) ; } else { first = first | ( 1 << ( str . charAt ( i ) - ' a ' ) ) ; } } for ( int i = 0 ; i < 26 ; i ++ ) { if ( ( ( first & ( 1 << i ) ) & ( second & ( 1 << i ) ) ) != 0 ) { System . out . print ( ( char ) ( i + ' a ' ) + " ▁ " ) ; } } } static public void main ( String args [ ] ) { String str = " geeksforgeeks " ; int N = str . length ( ) ; findDuplicate ( str , N ) ; } }