Backspace String Compare (LeetCode 844): Solution and Explanation

Easy
Two Pointers
String
Stack
Simulation

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

  1. Set i = len(s) - 1, j = len(t) - 1, skip_s = skip_t = 0.
  2. While i >= 0 or j >= 0: move i left past every '#' (adding to skip_s) and every letter it erases (subtracting from skip_s), stopping on a surviving letter.
  3. Do the same for j in t.
  4. Let a be s[i] or nothing if i < 0, and b likewise. If a != b, return false.
  5. Decrement i and j and continue. When the loop ends, return true.

Step-by-step example

s = "ab#c", t = "ad#c"
  1. s[3] = 'c' and t[3] = 'c' both survive (no backspace owed). They match, so step to i = 2, j = 2.
  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.
  3. Both survivors are 'a', so they match. Step to i = -1, j = -1.
  4. 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 True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

Each pointer only moves left, so every character of s and t is visited once.

Space

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.