Backspace String Compare

Let’s discuss an interesting problem Backspace String Compare.

Given two strings S and T containing backspaces. We have to write a code to check if they are equal.  In string, # means a backspace character.

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 = “#a#c”

Output: true

Explanation: Both S and T become “c”.

Example 4:

Input: S = “a#c”, T = “b”

Output: false

Explanation: S becomes “c” while T becomes “b”.

Backspace string compare

We have discussed the problem statement. Before checking the solution, spend a few minutes to think how you can approach this problem.

In this tutorial, I am going to discuss multiple approaches to solve this problem. Also, at the end of this post, i have shared the link to the video tutorial.

Backspace String Compare Solution using Stack | Java Code

The simplest approach to solve this problem is to use two stacks. Here are the following steps –

i) Declare two stacks.

ii) Perform the following operations for both the strings.

a) Traverse a string and pick one character at a time. If the character is not a backspace character (#) then push them into a stack.

b) If it’s a backspace character then pop out the last pushed character from a stack.

iii) After that compare both the stacks. If both are equal then return true else false.

The time complexity of this approach is O(n) and its space complexity is also O(n).

Backspace String Compare using Two Pointers – Java Code

In our previous approach, we have solved this problem using the stack data structure. Can we optimize our solution?

Yes, we can solve this problem using two pointers without using extra space.

Here are the following steps –

Traverse both the strings in reverse order. If any backspace(#) character is found, It means we have to skip the next non-backspace character. If a character isn’t skipped, it is part of the final answer.

The time complexity of this approach is O(n) and its space complexity is O(1).

Backspace String Compare Video Tutorial

Programming video tutorials

Programming Questions on Arrays

Programming Questions on Linked List

Programming Questions on String

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.