Backspace String Compare (LeetCode 844): Solution and Explanation
Two strings are typed into empty editors where '#' is a backspace. Decide whether the two final texts are equal.
Intuition
The direct approach is to simulate the editor: push each letter onto a stack, pop on '#', and compare the two stacks. That is O(n) time but also O(n) space, and the follow-up asks for constant space.
The key observation is about direction. A '#' only deletes something to its left. Reading left to right, you meet a letter before you know whether a later '#' will delete it. Reading right to left, every '#' is seen before the letter it deletes.
So walk each string backwards with a counter of backspaces owed. A '#' adds one to the counter. A letter while the counter is positive is erased and pays one back. A letter while the counter is zero survives, and it is the next character of the final text, read from the end.
Do this on both strings in lockstep: find the next survivor in s, the next survivor in t, and compare. If one string runs out while the other still has a survivor, or the survivors differ, the texts differ. If both run out together, they are equal.
Approach: Two pointers from the right with skip counters
- Set
i = len(s) - 1,j = len(t) - 1,skip_s = skip_t = 0. - While
i >= 0orj >= 0: moveileft past every '#' (adding toskip_s) and every letter it erases (subtracting fromskip_s), stopping on a surviving letter. - Do the same for
jin t. - Let
abes[i]or nothing ifi < 0, andblikewise. Ifa != b, return false. - Decrement
iandjand continue. When the loop ends, return true.
Step-by-step example
s = "ab#c", t = "ad#c"
- s[3] = 'c' and t[3] = 'c' both survive (no backspace owed). They match, so step to
i = 2,j = 2. - s[2] = '#' sets
skip_s = 1; s[1] = 'b' is erased; s[0] = 'a' survives. Likewise t[2] = '#' erases t[1] = 'd' and t[0] = 'a' survives. - Both survivors are 'a', so they match. Step to
i = -1,j = -1. - Both pointers are exhausted, so return true. Both strings type "ac".
Code: Python, Java, C++
1class Solution:
2 def backspaceCompare(self, s: str, t: str) -> bool:
3 i, j = len(s) - 1, len(t) - 1
4 skip_s = skip_t = 0
5 while i >= 0 or j >= 0:
6 while i >= 0:
7 if s[i] == '#':
8 skip_s += 1
9 elif skip_s > 0:
10 skip_s -= 1
11 else:
12 break
13 i -= 1
14 while j >= 0:
15 if t[j] == '#':
16 skip_t += 1
17 elif skip_t > 0:
18 skip_t -= 1
19 else:
20 break
21 j -= 1
22 a = s[i] if i >= 0 else ''
23 b = t[j] if j >= 0 else ''
24 if a != b:
25 return False
26 i -= 1
27 j -= 1
28 return True1class Solution {
2 public boolean backspaceCompare(String s, String t) {
3 int i = s.length() - 1, j = t.length() - 1;
4 int skipS = 0, skipT = 0;
5 while (i >= 0 || j >= 0) {
6 while (i >= 0) {
7 if (s.charAt(i) == '#') skipS++;
8 else if (skipS > 0) skipS--;
9 else break;
10 i--;
11 }
12 while (j >= 0) {
13 if (t.charAt(j) == '#') skipT++;
14 else if (skipT > 0) skipT--;
15 else break;
16 j--;
17 }
18 char a = i >= 0 ? s.charAt(i) : 0;
19 char b = j >= 0 ? t.charAt(j) : 0;
20 if (a != b) return false;
21 i--;
22 j--;
23 }
24 return true;
25 }
26}1class Solution {
2public:
3 bool backspaceCompare(string s, string t) {
4 int i = (int)s.size() - 1, j = (int)t.size() - 1;
5 int skipS = 0, skipT = 0;
6 while (i >= 0 || j >= 0) {
7 while (i >= 0) {
8 if (s[i] == '#') skipS++;
9 else if (skipS > 0) skipS--;
10 else break;
11 i--;
12 }
13 while (j >= 0) {
14 if (t[j] == '#') skipT++;
15 else if (skipT > 0) skipT--;
16 else break;
17 j--;
18 }
19 char a = i >= 0 ? s[i] : 0;
20 char b = j >= 0 ? t[j] : 0;
21 if (a != b) return false;
22 i--;
23 j--;
24 }
25 return true;
26 }
27};Time and space complexity
O(n + m)
Each pointer only moves left, so every character of s and t is visited once.
O(1)
Only two indices and two counters are kept.
Other approaches
Build both texts with a stack (time O(n + m), space O(n + m))
Push letters and pop on '#' (ignoring '#' on an empty stack), then compare the two results. Easy to get right and a good first answer, but uses O(n + m) memory.
Rewrite in place (time O(n + m), space O(1) with mutable arrays)
Use a write pointer to overwrite each array with its typed text (a letter writes and advances, a '#' steps the write pointer back), then compare prefixes. O(1) extra space, but it mutates the input, which strings in many languages do not allow.
Common mistakes
- Popping from an empty stack on a leading '#'. Backspace on an empty text does nothing.
- Comparing as soon as one string runs out. If i < 0 but t still has a survivor, the answer is false, so treat the exhausted side as an empty character.
- Resetting the skip counter between rounds. Pending backspaces carry over until a letter pays them back.
- Scanning left to right with a counter. A letter's fate depends on the '#' characters after it, so the forward scan cannot decide it in one pass.
Frequently asked questions
Why scan from the right instead of the left?
A '#' deletes the character before it. From the right, you always read the '#' first, so you know a letter is erased the moment you reach it. From the left, you would need to remember letters until you know whether they survive, which takes extra space.
What happens with more '#' than letters?
The extra backspaces stay in the counter and the pointer simply runs past the start of the string. That side then has no survivor, which is the same as an empty text.
Is the stack solution acceptable in an interview?
It is a good first answer. Interviewers usually ask the O(1)-space follow-up next, and the backward two-pointer scan is the expected improvement.