Super Reduced String

  • + 0 comments

    c++ solution without erasing or adding stuff to data structures - using previous left and right (pl and pr) indexes and an array to store elements that have been "erased" (used vector).

    string superReducedString(string s) { int n = s.size(); vector used(n,false); int pl = -1, pr = -1;

    int i = 0;
    while (i < n) {
        if (i+1 < n and s[i]==s[i+1]) {
            int l = !used[i] ? i : pl;
            int r = !used[i+1] ? i+1 : pr;
    
            while (l >= 0 and r < n) {
                if (s[l]!=s[r]) break;
    
                used[l]=used[r]=true;
    
                while (l>=0 and used[l]) l--;
                while (r<n and used[r]) r++;
            }
            pl = l, pr = r;
        }
        i=max(i+1,pr);
    }