← Back to Home

reverse thinking


There isn't always one way to solve a problem

844. Backspace String Compare

Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
  • Use stack and pop whenever we see #. But that's not O(1) space.
  • We could compare chars whichever is not removed by #. But we can't know if current char will remain or not if we go from start to end.
  • Traverse from reverse
public boolean backspaceCompare(String s, String t) {
        int i = s.length() - 1, j = t.length() - 1;
        // specifies how many chars we can skip
        int skipS = 0, skipT = 0; 
        while(i>=0 || j>=0){
            // find whats the last char after backspacing from right
            while(i >= 0){ 
                if(s.charAt(i) == '#') skipS++;
                else if(skipS > 0) skipS--;
                else break;
                i--;
            }
            while(j >= 0){
                if(t.charAt(j) == '#') skipT++;
                else if(skipT > 0) skipT--;
                else break;
                j--;
            }
            // If resulting last chars are different
            if(i >= 0 && j >= 0 && s.charAt(i) != t.charAt(j))
                return false;

            // One of them can't be empty string. Both or none
            if((i >= 0) != (j >= 0)) return false;

            i--; j--;
        }
        return true;
    }