844. Backspace String Compare
Asked at 11Google34Microsoft33Amazon29Meta22Bloomberg18Roku87Microstrategy78Wells Fargo65Agoda64Goldman Sachs33Salesforce28
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)))
assert Solution().backspaceCompare("ab#c", "ad#c") is True
assert Solution().backspaceCompare("ab##", "c#d#") is True
assert Solution().backspaceCompare("a#c", "b") is False
assert Solution().backspaceCompare("a##c", "#a#c") is True
assert Solution().backspaceCompare("bxj##tw", "bxo#j##tw") is True
assert Solution().backspaceCompare("ab", "b") is False
class Solution {
public boolean backspaceCompare(String s, String t) {
int i = s.length() - 1, j = t.length() - 1;
while (true) {
i = next(s, i);
j = next(t, j);
if (i < 0 || j < 0) return i < 0 && j < 0;
if (s.charAt(i--) != t.charAt(j--)) return false;
}
}
private int next(String x, int i) { // index of the next surviving char at or before i, or -1
for (int skip = 0; i >= 0; i--) {
if (x.charAt(i) == '#') skip++;
else if (skip > 0) skip--;
else break;
}
return i;
}
}
func backspaceCompare(s string, t string) bool {
// next returns the index of the next surviving character at or before i (-1 if none)
next := func(x string, i int) int {
skip := 0
for ; i >= 0; i-- {
if x[i] == '#' {
skip++
} else if skip > 0 {
skip--
} else {
break
}
}
return i
}
i, j := len(s)-1, len(t)-1
for {
i, j = next(s, i), next(t, j)
if i < 0 || j < 0 {
return i < 0 && j < 0
}
if s[i] != t[j] {
return false
}
i, j = i-1, j-1
}
}