Back to Dashboard

Comparing Strings containing Backspaces

Medium

Problem Statement

Given two strings containing backspaces (identified by the character ‘#’), check if the two strings are equal.

Examples

Example 1:

  • Input: s = "ab#c", t = "ad#c"
  • Output: true

Approach 1: Two Pointers

O(n)
O(1)
class Solution {
    public boolean backspaceCompare(String s, String t) {
        var i1 = s.length() - 1;
        var i2 = t.length() - 1;
        while (i1 >= 0 || i2 >= 0) {
            var p1 = findIndexAfterBackSpace(s, i1);
            var p2 = findIndexAfterBackSpace(t, i2);
            if (p1 < 0 && p2 < 0) {
                return true;
            }
            
            if (p1 < 0 || p2 < 0) {
                return false;
            }

            if (s.charAt(p1) != t.charAt(p2)) {
                return false;
            }
            i1 = p1 - 1;
            i2 = p2 - 1;
        }
        return true;
    }

    private int findIndexAfterBackSpace(String s, int i) {
        var bp = 0;
        while (i >= 0) {
            if (s.charAt(i) == '#') {
                bp ++;
            } else if (bp > 0) {
                bp --;
            } else {
                break;
            }
            i --;
        }
        return i;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

ArrayTwo Pointers

Date

2026-02-8
View Problem Source