Backspace String Compare

Easy

Topics
StringStackTwo Pointers

Given two strings s and t, return true if they are equal after typing them into empty text editors. # is a backspace character.

Example 1

sab#c
→ac
tad#c
→ac
Each # is a backspace. Both strings reduce to ac and ac, so the answer is true.
Each string is shown as typed and after the backspaces are applied.
Input:  s = "ab#c", t = "ad#c"
Output: true

Example 2

sa##c
→c
t#a#c
→c
Input:  s = "a##c", t = "#a#c"
Output: true

Example 3

sa#c
→c
tb
→b
Input:  s = "a#c", t = "b"
Output: false

Constraints

  • 1 <= s.length, t.length <= 200
  • s and t contain lowercase letters and #.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A # deletes the character before it, and the question is whether two strings are equal once every deletion is applied.

The direct reading gives the solution: walk left to right, pushing letters and popping on #, and whatever remains is the typed text. A stack is the right structure because deletion always targets the most recent surviving character, which is exactly the top.

Two details make it correct rather than nearly correct. A # on an empty stack is a no-op, not an error — backspacing into an empty box does nothing. And the deletions interact: "a##c" deletes the a and then has nothing left to delete, so it reduces to "c", which equals what "#a#c" reduces to.

Worth knowing there is an O(1)-space alternative, because it is the standard follow-up. Walk both strings from the right, maintaining a skip count: on a # increment skip, on a letter either consume a skip or yield the character for comparison. Right to left works where left to right would not, because a character's fate depends only on the # symbols that come after it.

Approach

  1. build(x): push letters, pop on # when the stack is non-empty, join at the end.
  2. Compare the two built strings.

Dry Run

s = "ab#c"          t = "ad#c"
  'a' push   [a]      'a' push   [a]
  'b' push   [a,b]    'd' push   [a,d]
  '#' pop    [a]      '#' pop    [a]
  'c' push   [a,c]    'c' push   [a,c]
  -> "ac"             -> "ac"          equal -> true

s = "a##c"          t = "#a#c"
  'a' push   [a]      '#' empty, no-op  []
  '#' pop    []       'a' push          [a]
  '#' empty, no-op [] '#' pop           []
  'c' push   [c]      'c' push          [c]
  -> "c"              -> "c"            equal -> true

The second pair is the one that breaks naive attempts: both strings contain a # with nothing to delete, and treating that as an error — or as deleting something — gives the wrong answer.

Complexity

  • Time — O(n + m): each character of each string is pushed and popped at most once.
  • Space — O(n + m): the two built strings. The two-pointer variant described above is O(1), comparing in place without materialising either result — that is the answer to expect as a follow-up, and the reason to mention it even though the stack version is what is shown.

Common Pitfalls

  • Popping without checking the stack is non-empty. A leading # is legal input and must be ignored, not an error.
  • Comparing lengths early to exit. Two strings of different raw lengths can reduce to the same text, which is the whole problem.
  • Deleting in place with string concatenation per #, which is O(n^2).
  • Trying the skip-count trick left to right. A character's survival depends on the # symbols after it, so the scan has to run right to left.
  • Treating # as a literal character to compare. It is an instruction, never part of the result.

Full Solution — all languages

class Solution:
    def backspaceCompare(self, s, t):
        def build(x):
            stack = []
            for c in x:
                if c == "#":
                    if stack: stack.pop()
                else:
                    stack.append(c)
            return "".join(stack)
        return build(s) == build(t)
Asked at Goldman Sachs
SensAI
Beta
Tap the mic to stop voice mode