sagelearnai

Backspace String Compare

Difficulty: Easy · Pattern: Stack & Monotonic Stack · LeetCode #844

# means backspace. Return true if s and t are equal after typing both into empty text editors. Follow-up: O(1) extra space.

Examples

text
s = "ab#c", t = "ad#c"  →  true    (both "ac")
s = "ab##", t = "c#d#"  →  true    (both "")
s = "a#c",  t = "b"     →  false

Hints

  1. A stack simulation is easy (O(n) space).
  2. For O(1) space, scan from the right: a # means skip the next real character to the left.

Approach

Two pointers from the end of each string. For each string, find the next character that survives: count #s as pending skips and skip characters while skips remain. Compare the surviving characters; if they differ (or only one string has one left), return false. O(n + m) time, O(1) space.

Complexity

Time: O(n + m). Space: O(1).

Python solution
def backspaceCompare(s, t):
    def next_valid(x, i):
        skip = 0
        while i >= 0:
            if x[i] == "#":
                skip += 1
            elif skip:
                skip -= 1
            else:
                return i
            i -= 1
        return -1
    i, j = len(s) - 1, len(t) - 1
    while True:
        i, j = next_valid(s, i), next_valid(t, j)
        if i < 0 or j < 0:
            return i < 0 and j < 0
        if s[i] != t[j]:
            return False
        i -= 1; j -= 1
JavaScript solution
function backspaceCompare(s, t) {
  const nextValid = (x, i) => { let skip = 0; for (; i >= 0; i--) { if (x[i] === '#') skip++; else if (skip) skip--; else return i; } return -1; };
  let i = s.length - 1, j = t.length - 1;
  for (;;) {
    i = nextValid(s, i); j = nextValid(t, j);
    if (i < 0 || j < 0) return i < 0 && j < 0;
    if (s[i] !== t[j]) return false;
    i--; j--;
  }
}