Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
'#' means skip the next real character to the left. Track how many skips are pending with skip_s and skip_t.i and jpoint to non-skipped characters, compare them directly. The key insight: you never need to build the processed strings — just find the next "surviving" char on each side.Proofreading from the end — you read backward, and when you see an eraser mark (#), you know the previous character was deleted. Keep counting erasers and skip accordingly until you find a surviving character to compare.
The most natural way to solve this is to simulate exactly what happens when you type the strings. We can use a stack: if we see a regular character, we push it onto the stack. If we see a '#', we pop from the stack (if it's not empty). Once we process both strings this way, we just check if the two stacks are identical.
build(string) that returns the parsed string.build, iterate through characters. Push to stack if it's a letter, pop if it's '#'.build(s) == build(t).Why it's not optimal: While this is O(n + m) time, it requires O(n + m) space to store the built strings. The follow-up challenges us to do this in O(1) space, which requires two pointers from the end.
def backspaceCompare(s, t): def build(string): stack = [] for char in string: if char != '#': stack.append(char) elif stack: stack.pop() return "".join(stack) return build(s) == build(t)
Instead of building the processed strings, scan both from right to left, maintaining skip counters. Whenever we see '#', we increment the skip count. When we see a letter and the skip count is positive, we skip that letter (it was erased).
i = len(s)-1, j = len(t)-1, skip_s = skip_t = 0.i leftward: skip '#' chars (increment skip) and erased chars (decrement skip). Stop at the next surviving char.j.i and j. If they differ, return False. If one is exhausted but not the other, return False.True.
Discussion
…