Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

844. Backspace String Compare - Leetcode Solution

Code Implementation

class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        def build(string):
            res = []
            for char in string:
                if char != '#':
                    res.append(char)
                elif res:
                    res.pop()
            return res
        return build(S) == build(T)
      
class Solution {
public:
    bool backspaceCompare(string S, string T) {
        return build(S) == build(T);
    }
private:
    string build(const string& str) {
        string res;
        for (char c : str) {
            if (c != '#')
                res.push_back(c);
            else if (!res.empty())
                res.pop_back();
        }
        return res;
    }
};
      
class Solution {
    public boolean backspaceCompare(String S, String T) {
        return build(S).equals(build(T));
    }
    private String build(String str) {
        StringBuilder res = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (c != '#')
                res.append(c);
            else if (res.length() > 0)
                res.deleteCharAt(res.length() - 1);
        }
        return res.toString();
    }
}
      
var backspaceCompare = function(S, T) {
    function build(str) {
        let res = [];
        for (let c of str) {
            if (c !== '#') {
                res.push(c);
            } else if (res.length) {
                res.pop();
            }
        }
        return res.join('');
    }
    return build(S) === build(T);
};
      

Problem Description

Given two strings S and T, return true if they are equal when both are typed into empty text editors. In these editors, the # character means a backspace, so it erases the character before it (if any). After processing all the characters in both strings, compare the results.

  • Each # acts as a backspace and removes the previous character, if one exists.
  • Return true if both processed strings are identical, false otherwise.
  • Both input strings may contain lowercase letters and the # character.

Thought Process

The problem asks us to simulate how typing works in a basic text editor with backspace support. The most direct approach is to process each string and simulate the effect of backspaces, then compare the final results.

  • First, we could try to process the string by iterating from left to right, keeping track of the current result.
  • Whenever we see a letter, we add it to our current result; when we see a #, we remove the last added character (if any).
  • We repeat this for both strings and compare the results.
  • Alternatively, we might consider a more optimized approach to avoid extra space, but it’s important to first understand the basic simulation.

This approach is both intuitive (like using a stack or a list) and easy to implement. Optimization can be considered once the core logic is understood.

Solution Approach

We can solve this problem by simulating the typing process for both strings:

  1. Simulate Typing with a Stack/List:
    • Initialize an empty list (or stack) to represent the current state of the text editor.
    • Iterate through each character in the string:
      • If the character is not #, append it to the list.
      • If the character is # and the list is not empty, remove (pop) the last character from the list.
    • After processing, join the list to form the final string.
  2. Compare Results:
    • Process both S and T using the above simulation.
    • Compare the final strings; if they are the same, return true, else return false.

This method is straightforward and leverages the stack/list structure to simulate the backspace behavior efficiently.

Example Walkthrough

Let's consider the example: S = "ab#c", T = "ad#c"

  • Process S:
    • Add 'a' → ['a']
    • Add 'b' → ['a', 'b']
    • Backspace '#' → remove 'b' → ['a']
    • Add 'c' → ['a', 'c']
    Final result: "ac"
  • Process T:
    • Add 'a' → ['a']
    • Add 'd' → ['a', 'd']
    • Backspace '#' → remove 'd' → ['a']
    • Add 'c' → ['a', 'c']
    Final result: "ac"
  • Since both processed strings are "ac", the function returns true.

Time and Space Complexity

  • Brute-force Approach:
    • Process each string character by character, simulating the backspace.
    • Time Complexity: O(N + M) where N and M are the lengths of S and T.
    • Space Complexity: O(N + M) due to storing the processed strings.
  • Optimized Approach (Two Pointers):
    • We can process both strings from the end using two pointers and skip characters as needed, potentially reducing space to O(1) (not shown above).
    • Time Complexity remains O(N + M).
    • Space Complexity: O(1) if not storing the processed strings.
  • For the stack/list approach shown in the code, both time and space complexity are linear in the size of the inputs.

Summary

The Backspace String Compare problem is efficiently solved by simulating the effect of backspaces using a stack or list. By processing each string and handling backspaces as they appear, we can easily compare the final results. The approach is intuitive, leverages basic data structures, and can be optimized further if needed. This method highlights the power of simulating real-world processes with simple programming constructs.