15% off all plans & roadmaps Use code

See plans

Backspace String Compare

Updated

TL;DR: Two strings match when their backspaced results are equal. Scan both strings from the right, keep a count of pending backspaces for each, and compare only the letters that survive.

Problem

Given two strings s and t, return true if they are equal when both are typed into empty text editors. The character '#' means a backspace. A backspace removes the character before it.

If a backspace is typed on an empty text, the text stays empty.

Example 1

Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".

Example 2

Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".

Example 3

Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c", while t becomes "b".

Constraints

  • 1 <= s.length, t.length <= 200
  • s and t only contain lowercase letters and '#' characters.

Constraints that matter

  • Lengths up to 200 make a quadratic scan affordable, but the follow-up asks for O(1) extra space, which rules out building the typed text.
  • The only special character is #, so a letter is either deleted or kept, and you can compare kept letters directly.
  • Both texts can end up empty, as in ab## and c#d#. The final check must confirm that both pointers ran out at the same time.

View on LeetCode

Hints

Hint 1

This problem compares two results that come from a reduction rule.

Hint 2

Type each string into a stack, the same way an editor works.

Solution

Intuition

This problem compares two results that come from a reduction rule. Each # removes the letter before it, and the result is only known after the whole string is read. Reading left to right, you see a backspace after the letter it deletes, so you must hold on to every letter until the end. That is the cost of the naive method.

Picture reading a paper tape from its end, where each backspace key is a tally in your pocket. If you hold a tally when you reach a letter, you throw that letter away and drop one tally. The pocket count is skipS, and the letters you keep are the ones you compare.

Read the strings from right to left and the order flips. A # now appears before the letter it deletes. A counter of pending backspaces tells you whether the current letter survives.

Each string gets its own pointer and counter, and both pointers only move left. This is the two pointers pattern applied to string comparison with backspaces.

Stop each pointer on a surviving letter, compare the two letters, then move both pointers left. If one string runs out first, the surviving letters differ in count, so the answer is false. If both run out together, the reduced strings matched at every position.

Watch the pattern animation

Worked example

Input: s = "xy##z#w#v##", t = "z#w#"
Output: true
Explanation: Typing s leaves nothing, because the trailing ## clears the v and the earlier letters are cleared by the other backspaces. Typing t also leaves nothing, since z and w are each erased by the # that follows them. Both editors end empty, so the answer is true.

Approach 1: Brute force with a stack

Type each string into a stack, the same way an editor works. A letter goes on the stack, and a # removes the top letter when the stack has one. After both strings are typed, compare the two stacks. This is the most direct model of the problem.

The cost is memory. Each stack can hold as many letters as its string, and the two stacks exist at the same time. The comparison also rebuilds the full reduced text for each string, even though you only need to check it letter by letter.

Steps

  1. Create an empty stack for s and an empty stack for t.
  2. Walk through s from left to right. Push each letter. On #, pop if the stack is not empty.
  3. Repeat the same walk for t with its own stack.
  4. Compare the two stacks element by element. Return true only if they have the same length and the same letters in the same order.

Dry run

Typing s = "xy##z#w#v##" into a stack:

  • x gives [x]. y gives [x, y].
  • # pops y, leaving [x]. The second # pops x, leaving [].
  • z gives [z]. # leaves [].
  • w gives [w]. # leaves [].
  • v gives [v]. The first # leaves [], and the second # finds the stack empty, so it does nothing.

The stack for s is empty.

Typing t = "z#w#":

  • z gives [z]. # leaves [].
  • w gives [w]. # leaves [].

The stack for t is also empty. The two stacks match, so the answer is true.

Complexity

TimeO(n + m)
SpaceO(n + m)

Let n be the length of s and m the length of t. Each character causes at most one push or one pop, and each string is read once, so building both stacks costs O(n + m). The final comparison walks at most min(n, m) positions before it either finds a mismatch or a length difference. The stacks can hold up to n and m letters at the same time, so the extra space is O(n + m).

PythonTested in our runner

class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        def build(text: str) -> str:
            stack = []
            for ch in text:
                if ch == '#':
                    if stack:
                        stack.pop()
                else:
                    stack.append(ch)
            return ''.join(stack)

        return build(s) == build(t)

The String Comparison with Backspaces infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

String Comparison with Backspaces

Part of Two Pointers

Approach 2: Two pointers from the right with skip countersOptimalString Comparison with Backspaces

What is slow: the stack keeps every surviving letter, so the memory grows with the input, and both reduced strings are rebuilt only to be compared. Most of that work is wasted, because you compare them one letter at a time anyway.

The insight that fixes it: scanning from the right, each # is seen before the letter it deletes. A counter per string tells you whether the current letter is deleted. Skip deleted letters, stop on a survivor, compare the two survivors, and move on. No text is stored, so the extra space is constant.

Why it is correct. Each # deletes the nearest surviving letter to its left, so a right-to-left scan with a counter of unmatched backspaces finds exactly the survivors. The invariant is that skipS equals the number of backspaces still waiting for a letter to delete. Survivors found this way are the same letters the forward stack would keep, so the first mismatch is a real mismatch.

Steps

  1. Set i to the last index of s, j to the last index of t, and both skip counters to 0.
  2. Move i left. On #, increase skipS. On a letter with skipS above 0, decrease skipS. Stop on a letter with skipS at 0, or when i is below 0.
  3. Do the same for j with skipT.
  4. If either pointer is below 0, return true only when both are below 0.
  5. If the two stopped letters differ, return false. Otherwise move both pointers left and repeat from step 2.

Dry run

The example is s = "xy##z#w#v##" and t = "z#w#", with i = 10 and j = 3. Each row is one index the pointer visits.

StepStringIndexCharEffectskipSskipT
1s10#count a pending backspace10
2s9#count another20
3s8vdeleted, uses one backspace10
4s7#count another20
5s6wdeleted10
6s5#count another20
7s4zdeleted10
8s3#count another20
9s2#count another30
10s1ydeleted20
11s0xdeleted, i reaches -110
12t3#count a pending backspace11
13t2wdeleted10
14t1#count another11
15t0zdeleted, j reaches -110

Both pointers are below 0, so the function returns true. No letter pair was compared, because every letter in both strings was deleted.

Complexity

TimeO(n + m)
SpaceO(1)

Let n be the length of s and m the length of t. The pointers i and j only move left and never reset, so each index is visited at most once across all rounds. Each round makes at most one comparison, and a round only starts when both strings still have letters left, so there are at most min(n, m) rounds, and the total work is O(n + m). The algorithm stores two indexes and two counters, which is O(1) extra space.

PythonTested in our runner

class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        i, j = len(s) - 1, len(t) - 1
        skip_s = skip_t = 0
        while True:
            # Move i left to the next surviving letter in s
            while i >= 0:
                if s[i] == '#':
                    skip_s += 1
                elif skip_s > 0:
                    skip_s -= 1
                else:
                    break
                i -= 1
            # Same for t
            while j >= 0:
                if t[j] == '#':
                    skip_t += 1
                elif skip_t > 0:
                    skip_t -= 1
                else:
                    break
                j -= 1
            if i < 0 or j < 0:
                # Both must be exhausted at the same time
                return i < 0 and j < 0
            if s[i] != t[j]:
                return False
            i -= 1
            j -= 1

Common mistakes

  • skip_s -= 1 on a #. The counter must go up on # and down only when a letter is deleted. Decrementing on # makes the counter negative and deletes the wrong letters.
  • if i < 0 or j < 0: return True. This accepts s = "a#" and t = "b", where s is empty and t is b. The fix is to return i < 0 and j < 0.
  • Reading s[i] after i has reached -1. In Python, s[-1] silently returns the last character, so the bounds check must run before the index is used.
  • Comparing raw characters before skipping deleted ones, as in s[i] != t[j] on the first pass. For ab#c and ac, the raw c and c match, but the raw b on the next step is wrong. Skip on both sides first.
  • Scanning left to right with one counter of pending deletions. The counter tells you how many letters to remove, but not which ones, so the forward scan needs a stack. Reading right to left removes this problem.

Edge cases

  • s = "#", t = "a#": both reduce to empty, so the answer is true.
  • s = "a#", t = "b": s is empty and t keeps b, so the answer is false.
  • s = "##a", t = "a": leading backspaces do nothing, so the answer is true.
  • s = "a###", t = "b#": the extra backspaces are harmless. s is empty and t is empty, so the answer is true.
  • Two identical strings of 200 lowercase letters with no #: the answer is true, and the scan takes one step per character on each side.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Backspace String Compare, with how to answer them.

Unlock the follow-ups

Backspace String Compare FAQ

What is the time complexity of Backspace String Compare?

The optimal solution runs in O(n + m) time, where n and m are the lengths of s and t. Each pointer only moves left, so every character is visited once. The brute force stack method has the same time bound.

Why use two pointers for Backspace String Compare?

Scanning from the right puts each # before the letter it deletes, so one counter per string decides whether a letter survives. Two pointers let you compare the surviving letters in place. The stack method stores those letters instead, which costs linear memory.

Can Backspace String Compare be solved in O(1) extra space?

Yes. The right-to-left scan keeps two indexes and two counters, and it never builds the reduced strings. The stack approach needs O(n + m) extra space because it stores both reduced strings.

Does a stack work for Backspace String Compare?

Yes. A stack is the most direct model of typing, and it gives the correct answer. It costs linear extra memory, so it does not meet the O(1) space follow-up.

Asked at

See which companies ask this — Pro

Practise it