Remove duplicates from a string in O ( 1 ) extra space | C ++ implementation of above approach ; Function to remove duplicates ; keeps track of visited characters ; gets character value ; keeps track of length of resultant string ; check if Xth bit of counter is unset ; mark current character as visited ; Driver code
#include <bits/stdc++.h> NEW_LINE #include <string> NEW_LINE using namespace std ; string removeDuplicatesFromString ( string str ) { int counter = 0 ; int i = 0 ; int size = str . size ( ) ; int x ; int length = 0 ; while ( i < size ) { x = str [ i ] - 97 ; if ( ( counter & ( 1 << x ) ) == 0 ) { str [ length ] = ' a ' + x ; counter = counter | ( 1 << x ) ; length ++ ; } i ++ ; } return str . substr ( 0 , length ) ; } int main ( ) { string str = " geeksforgeeks " ; cout << removeDuplicatesFromString ( str ) ; return 0 ; }