C++ program to remove duplicate characters from string This is a question in the book "Cracking The Coding Interview". 


  Design an algorithm and write code to remove the duplicate characters in a string
  without using any additional buffer. NOTE: One or two additional variables are fine.
  An extra copy of the array is not.
  
  Follow Up
  
  Write the test cases for this method.  The four test cases are    
  
  
  String does not contain any duplicates, e.g.: abcd
  String contains all duplicates, e.g.: aaaa
  Null string
  String with all continuous duplicates, e.g.: aaabbb
  


I want to optimise this code and whether I can use some other function from STL.

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;algorithm&gt;

std::string &amp; removeDuplicate(std::string&amp; str)
{
  int length = str.length();
  for(unsigned int i = 0; i &lt; length; i++)
  {
    char currChar = str[i]; //holds current character
    for(unsigned int j = i+1; j &lt; length; j++)
    {
      if(currChar == str[j])
        str.erase (std::remove(str.begin()+j, str.end(), str[j]), str.end());
    }
  }
  return str;
}

int main()
{
  std::string str;
  std::cout &lt;&lt; "Enter string \n";
  std::getline(std::cin, str);
  str = removeDuplicate(str);
  std::cout &lt;&lt;"New String is " &lt;&lt; str &lt;&lt; "\n";
}
From the tests we are if we are only looking for repeating chars, not duplicate e.g. we can transform "ABBA" into "ABA"  (and not "AB"). Then we can use something like:

void removeRepeatingChars(char* s){
  if(!s[0]){                  // Check for enpty string
    return;                   // Notning to do per definition 
  }

  int last=0;                 // Store position of last seen character  thats not a duplicate

  for(int i = 1; s[i] ; i++){ // Loop over all characters and
    if(s[i] != s[last]){      // check if current character is not a dupllicate.
      last++;                 // If so increment the position of last non duplicate and 
      s[last] = s[i];         // copy the currentcharacter to this position.
    }                         // Else go to next char.                            
  }  
  s[++last] = '\0';           // Add string terminator at the end.
}


If not you need to store each seen character and add this check so we get something like.

for(int i = 1; s[i] ; i++){ 
  if(s[i] != s[last] &amp;&amp; !sceen[s[i]]){
      last++;
      s[last] = s[i];
      seen[s[i]] = true;
  }
}


Observe that we use that we can modify the string how ever we like on chars we already have checked in order to do the whole operation in place.