Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

Two strings equal after their backspaces

Easy · Target 12 minutes · Two pointers· Type asked at

You're given two strings s and t made of lower-case letters and #. Each one is what somebody typed, and a # is a backspace that deletes the letter before it, if there is one. Return true if the two strings end up as the same text. Can you do it in O(1) extra space?

Examples

InputOutputWhy
s = "ab#c", t = "ad#c"trueThe b and the d both get deleted so each of them types ac.
s = "ab##", t = "c#d#"trueEvery letter in both of them gets deleted and they end up as two empty strings.
s = "a#c", t = "b"falseThe first one types c and the second types b, so they come out different.
s = "#a#c", t = "a##c"trueA backspace with nothing in front of it does nothing and both of them type ac.

Constraints

  • 1 ≤ s.length, t.length ≤ 200
  • s and t hold lower-case letters and '#' only

Hints

Hint 1

With a stack for each string it's easy enough and it costs you O(n) space, so what is it that stops you doing it in place from the front?

Hint 2

From the front you don't know whether a letter's going to survive until you've seen what comes after it, but from the back you've already seen every # that could delete it.

Hint 3

Walk a pointer back through each string with a count of the backspaces you still owe, skip letters while that count's above zero and then compare the two letters you land on.

Where people lose marks

  • Reading from the front with a pointer on each string, where you can't tell yet whether a letter's going to survive and you'll end up comparing letters that get deleted later on.
  • Stopping as soon as one string runs out, when you've still got to check that the other one doesn't have any letters left that survive.
  • Letting a # at the very start of a string do something, when there's nothing in front of it to delete and the count it adds just never gets used.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.