Remove duplicates from a string in O ( 1 ) extra space | C ++ implementation of above approach ; Method to remove duplicates ; Table to keep track of visited characters ; To keep track of end index of resultant string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeDuplicatesFromString ( string str ) { vector < int > table ( 256 , 0 ) ; vector < char > chars ; for ( auto i : str ) chars . push_back ( i ) ; int endIndex = 0 ; for ( int i = 0 ; i < chars . size ( ) ; i ++ ) { if ( table [ chars [ i ] ] == 0 ) { table [ chars [ i ] ] = -1 ; chars [ endIndex ++ ] = chars [ i ] ; } } string ans = " " ; for ( int i = 0 ; i < endIndex ; i ++ ) ans += chars [ i ] ; return ans ; } int main ( ) { string str = " geeksforgeeks " ; cout << ( removeDuplicatesFromString ( str ) ) << endl ; }