0

Question - Given a string s, remove all its adjacent duplicate characters recursively.

MY CODE:

string remove(string s){
if(s . size() == 0){
        return s ;
    }
    string ans ;
    int j = 0, count = 1 ;
    for(j = 0 ; j <= (s . size()-2) ; j++){
        if(s[j] == s[j+1]){
            count++ ;
        }
        else{
            if(count == 1){
                ans.push_back(s[j]) ;
            }
            else{
                count = 1 ;
            }
        }
    }
    if(count == 1){
        ans.push_back(s[j]) ;
    }
    if(s.size() == ans.size()){
        return ans ;
    }
    return remove(ans) ;    
}

This code works fine for all the inputs except for the input with size 1, if I replace j<=s.size()-2 with j< s.size()-1, it works fine for input with size 1 too. I am not able to figure out what's wrong with the above code why its showing runtime error with the above code.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
va_0511
  • 21
  • 3
  • If an input string `s` has a size of 1, then looping through `s` using `j <= (s.size()-2)` will cause `j` to go out of bounds of `s`. Looping using `j< s.size()-1` instead will not. – Remy Lebeau Nov 02 '21 at 19:04
  • 1
    Does this answer your question? [C++ string size minus integer is not the expected value, why?](https://stackoverflow.com/questions/52666447/c-string-size-minus-integer-is-not-the-expected-value-why) – JaMiT Nov 02 '21 at 19:10
  • You asked "why" rather than "how to avoid in the future". But as a bonus, __how to avoid in the future:__ don't think in terms of how big your loop control variable (`j`, in this example) can get; think in terms of how big your indices can get. Inside your loop, you use the indices `j` and `j+1`, so you need `j < s.size() && j+1 < s.size()`, which simplifies to `j+1 < s.size()`. Don't be tempted to re-arrange this to `j < s.size()-1` or to `j < s.size()-2`. I have a longer writeup at [A: Why does this happen at the end of the for loop with vectors](https://stackoverflow.com/a/69599487). – JaMiT Nov 02 '21 at 19:19
  • FYI, you are passing a **copy** of the string to the function. Any modifications will be made to a **copy** of the string. If you want to modify the parameter, pass by reference. – Thomas Matthews Nov 02 '21 at 21:30

0 Answers0