SDE & MLE Prep

844. Backspace String Compare

Problem

In s and t, the character # is a backspace that erases the character before it (if any). Decide whether the two strings are equal after applying the backspaces.

Example: s = "ab#c", t = "ad#c" → true; s = "a#c", t = "b" → false

Constraints: follow-up: O(n) time and O(1) space.

A stack works (O(n) space). For O(1) space walk both strings from the end: count pending #s and skip that many characters; compare the surviving characters one by one.

Complexity: O(n + m) time, O(1) space.

class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        def survivors(x):                  # surviving characters, right to left
            skip = 0
            for ch in reversed(x):
                if ch == "#":
                    skip += 1
                elif skip:
                    skip -= 1
                else:
                    yield ch

        return all(a == b for a, b in itertools.zip_longest(survivors(s), survivors(t)))