medium Comparing Strings containing Backspaces
Problem Statement
Given two strings containing backspaces (identified by the character ‘#’), check if the two strings are equal.
Example 1:
Input: str1="xy#z", str2="xzz#"
Output: true
Explanation: After applying backspaces the strings become "xz" and "xz" respectively.
Example 2:
Input: str1="xy#z", str2="xyz#"
Output: false
Explanation: After applying backspaces the strings become "xz" and "xy" respectively.
Example 3:
Input: str1="xp#", str2="xyz##"
Output: true
Explanation: After applying backspaces the strings become "x" and "x" respectively.
In "xyz##", the first '#' removes the character 'z' and the second '#' removes the character 'y'.
Example 4:
Input: str1="xywrrmp", str2="xywrrmu#p"
Output: true
Explanation: After applying backspaces the strings become "xywrrmp" and "xywrrmp" respectively.
Constraints:
1 <= str1.length, str2.length <= 200str1andstr2only contain lowercase letters and '#' characters.
Try it yourself
Try solving this question here:
✅ Solution Comparing Strings containing Backspaces
Problem Statement
Given two strings containing backspaces (identified by the character ‘#’), check if the two strings are equal.
Example 1:
Input: str1="xy#z", str2="xzz#"
Output: true
Explanation: After applying backspaces the strings become "xz" and "xz" respectively.
Example 2:
Input: str1="xy#z", str2="xyz#"
Output: false
Explanation: After applying backspaces the strings become "xz" and "xy" respectively.
Example 3:
Input: str1="xp#", str2="xyz##"
Output: true
Explanation: After applying backspaces the strings become "x" and "x" respectively.
In "xyz##", the first '#' removes the character 'z' and the second '#' removes the character 'y'.
Example 4:
Input: str1="xywrrmp", str2="xywrrmu#p"
Output: true
Explanation: After applying backspaces the strings become "xywrrmp" and "xywrrmp" respectively.
Constraints:
1 <= str1.length, str2.length <= 200str1andstr2only contain lowercase letters and '#' characters.
Solution
To compare the given strings, first, we need to apply the backspaces. An efficient way to do this would be from the end of both the strings. We can have separate pointers, pointing to the last element of the given strings. We can start comparing the characters pointed out by both the pointers to see if the strings are equal. If, at any stage, the character pointed out by any of the pointers is a backspace (’#’), we will skip and apply the backspace until we have a valid character available for comparison.
Here's a detailed walkthrough of the algorithm:
-
In the
comparefunction, two pointers are initialized,index1andindex2, to the last index ofstr1andstr2, respectively. -
A while loop is started which continues until both pointers are less than zero, that is, both have traversed their strings completely in a reverse manner.
-
Inside this loop, for each string, the
getNextValidCharIndexfunction is called with the current pointer. This function returns the index of the next valid character in the string (traversing from back to front) by taking into account the backspace characters.i1andi2point to the index of the next valid character in the two strings. -
If both
i1andi2are less than zero, it means the end of both strings has been reached, and the strings are considered equal. -
If only one of
i1ori2is less than zero, it means the end of one string has been reached, but not the other, and the strings are not equal. -
If the characters at indices
i1andi2are not the same, the strings are not equal. -
If none of the above conditions are met, the loop continues to the next valid characters in both strings.
-
The
getNextValidCharIndexfunction accepts a string and an index, and uses a backspace count to keep track of how many backspaces have been encountered. It then loops through the string backwards from the provided index until it encounters a valid character or reaches the beginning of the string. -
If a backspace character is found, the backspace count is incremented. If a non-backspace character is found and there are any counted backspaces, one backspace is subtracted from the count (to simulate the removal of the previous character), and the loop continues. If a non-backspace character is found and there are no backspaces left to account for, the loop breaks and the index of the valid character is returned.
Algorithm Walkthrough
Input: str1 = "xp#", str2 = "xyz##"
- Initial pointers:
index1 = 2,index2 = 4 - Process
str1(xp#):index1 = 2(points to#): incrementbackspaceCount = 1, moveindex1 to 1index1 = 1(points top): decrementbackspaceCount = 0, moveindex1 to 0index1 = 0(points tox): valid character found
- Process
str2(xyz##):index2 = 4(points to#): incrementbackspaceCount = 1, moveindex2 to 3index2 = 3(points to#): incrementbackspaceCount = 2, moveindex2 to 2index2 = 2(points toz): decrementbackspaceCount = 1, moveindex2 to 1index2 = 1(points toy): decrementbackspaceCount = 0, moveindex2 to 0index2 = 0(points tox): valid character found
- Compare characters:
- Both characters are
x(equal), moveindex1to-1andindex2to-1
- Both characters are
- End of strings: Both pointers are less than zero, strings are equal.
Here is the visual representation of this algorithm for Example 2:
Code
Here is what our algorithm will look like:
class Solution {
public boolean compare(String str1, String str2) {
// use two pointer approach to compare the strings
int index1 = str1.length() - 1, index2 = str2.length() - 1;
while (index1 >= 0 || index2 >= 0) {
int i1 = getNextValidCharIndex(str1, index1);
int i2 = getNextValidCharIndex(str2, index2);
if (
i1 < 0 && i2 < 0
) return true; // reached the end of both the strings
if (
i1 < 0 || i2 < 0
) return false; // reached the end of one of the strings
if (
str1.charAt(i1) != str2.charAt(i2)
) return false; // check if the characters are equal
index1 = i1 - 1;
index2 = i2 - 1;
}
return true;
}
private static int getNextValidCharIndex(String str, int index) {
int backspaceCount = 0;
while (index >= 0) {
if (
str.charAt(index) == '#'
) backspaceCount++; // found a backspace character
else if (
backspaceCount > 0
) backspaceCount--; // a non-backspace character
else break;
index--; // skip a backspace or a valid character
}
return index;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.compare("xy#z", "xzz#"));
System.out.println(sol.compare("xy#z", "xyz#"));
System.out.println(sol.compare("xp#", "xyz##"));
System.out.println(sol.compare("xywrrmp", "xywrrmu#p"));
}
}
Complexity Analysis
Time Complexity
-
Outer while loop: The
compare()method runs a while loop as long as eitherindex1orindex2is greater than or equal to 0. This loop processes each character in both strings from right to left. Each iteration of the loop involves finding the next valid character usinggetNextValidCharIndex(). -
getNextValidCharIndex() method: The
getNextValidCharIndex()method processes each character of the string at most once. When encountering a#(backspace), it increments thebackspaceCount, and when it encounters a valid character after processing backspaces, it returns the index of the valid character.- Each character is either counted or skipped exactly once. Therefore, the time complexity of this method is
, where Nis the length of the string.
- Each character is either counted or skipped exactly once. Therefore, the time complexity of this method is
Overall time complexity: The two strings are processed independently, so the overall time complexity is N and M are the lengths of the two strings str1 and str2, respectively.
Space Complexity
-
Constant space usage: The algorithm uses a few integer variables (
index1,index2,backspaceCount) to track positions and counts. These variables take up constant space. -
No additional data structures: The algorithm does not use any data structures that scale with the input size, as it works directly on the strings and uses only a fixed amount of space for the pointers and counts.
Overall space complexity:
🤖 Don't fully get this? Learn it with Claude
Stuck on Comparing Strings containing Backspaces? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Comparing Strings containing Backspaces** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Comparing Strings containing Backspaces** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Comparing Strings containing Backspaces**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Comparing Strings containing Backspaces**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.