Intervue featured on Shark TankIntervue featured on Shark Tank - mobile banner

Backspace String Compare

Given two strings containing backspace characters, compare the final strings after applying the backspace operations.

Constraints:

  • 1 <= s.length, t.length <= 200
  • s and t only contain lowercase letters and '#' characters.

Examples:

Input: "ab#c","ad#c"

Output: true

Explanation: Applying the backspace operations, we get "ac" for both strings.

Solutions

Two-Pointer Approach

Time: O(n + m)Space: O(n + m)

We use a two-pointer approach to build the final strings after applying the backspace operations. We iterate through each string, and whenever we encounter a '#', we remove the last character from the string if it's not empty.


class Solution {
  
  
  public:
  bool backspaceCompare(string s, string t) {
    
    return build(s) == build(t);
    
  }
  
  
  string build(string s) {
    
    string res;
    
    for (char c : s) {
      
      if (c != '#') {
        
        res += c;
        
      }
      else if (!res.empty()) {
        
        res.pop_back();
        
      }
      
    }
    
    return res;
    
  }
  
}
;

Difficulty: Medium

Category: String Manipulation

Frequency: High

Company tags:

GoogleAmazonFacebook