Check if two strings after processing backspace character are equal or not
Last Updated :
12 Apr, 2023
Given two strings s1 and s2, let us assume that while typing the strings there were some backspaces encountered which are represented by #. The task is to determine whether the resultant strings after processing the backspace character would be equal or not.
Examples:
Input: s1= geee#e#ks, s2 = gee##eeks
Output: True
Explanation: Both the strings after processing the backspace character becomes "geeeeks". Hence, true.
Input: s1 = equ#ual, s2 = ee#quaal#
Output: False
Explanation: String 1 = equ#ual, after processing the backspace character becomes "equal" whereas string 2 = equ#ual, after processing the backspace character becomes "equaa". Hence, false.
Approach:
To solve the problem mentioned above we have to observe that if the first character is '#', that is there is certainly no character typed initially and hence we perform no operation. When we encounter any character other than '#', then we add the character just after the current index. When we encounter a '#', we move one index back, so instead of deleting the character, we just ignore it. Then finally compare the two strings by comparing each character from start to end.
Below is the implementation of the above approach:
C++
/* C++ implementation to Check if
two strings after processing
backspace character are equal or not*/
#include <bits/stdc++.h>
using namespace std;
// function to compare the two strings
string removeBackspaces(string& s)
{
int n = s.size();
// To point at position after considering the
// backspaces
int idx = 0;
for (int i = 0; i < n; i++) {
if (s[i] != '#') {
s[idx] = s[i];
idx++;
}
else if (s[i] == '#' && idx >= 0) {
idx--;
}
// This idx can never point at negative index
// position
if (idx < 0)
idx = 0;
}
return s.substr(0, idx);
}
// Driver code
int main()
{
// initialise two strings
string s = "equ#ual";
string t = "gee##eeks";
if (removeBackspaces(s) == removeBackspaces(t))
cout << "True";
else
cout << "False";
return 0;
}
Java
/* Java implementation to Check if
two strings after processing
backspace character are equal or not*/
import java.io.*;
public class Main {
// function to compare the two strings
public static String removeBackspaces(String s) {
int n = s.length();
// To point at position after considering the
// backspaces
int idx = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) != '#') {
s = s.substring(0, idx) + s.charAt(i) + s.substring(idx + 1);
idx++;
}
else if (s.charAt(i) == '#' && idx >= 0) {
idx--;
}
// This idx can never point at negative index
// position
if (idx < 0)
idx = 0;
}
return s.substring(0, idx);
}
// Driver code
public static void main(String[] args) {
// initialise two strings
String s = "equ#ual";
String t = "gee##eeks";
if (removeBackspaces(s).equals(removeBackspaces(t)))
System.out.println("True");
else
System.out.println("False");
}
}
// This code is contributed by ritaagarwal.
Python3
# Python implementation to Check if two strings after processing backspace character are equal or not
# function to compare the two strings
def removeBackspace(s) -> str:
n = len(s)
# To point at position after considering the backspaces
idx = 0
for i in range(0, n):
if(s[i] != '#'):
s = s[:idx] + s[i] + s[idx+1:]
idx += 1
elif(s[i] == '#' and idx >= 0):
idx -= 1
# This idx can never point at negative index position
if(idx < 0):
idx = 0
ans = ""
for i in range(0, idx):
ans += s[i]
return ans
# Driver code
s = "equ#ual"
t = "gee##eeks"
if(removeBackspace(s) == removeBackspace(t)):
print("TRUE")
else:
print("FALSE")
C#
// C# implementation of above approach
using System;
class GFG {
// function to compare the two strings
static string removeBackspaces(string s)
{
int n = s.Length;
char[] ch = s.ToCharArray();
// To point at position after considering the
// backspaces
int idx = 0;
for (int i = 0; i < n; i++) {
if (s[i] != '#') {
ch[idx] = s[i];
idx++;
}
else if (s[i] == '#' && idx >= 0) {
idx--;
}
// This idx can never point at negative index
// position
if (idx < 0)
idx = 0;
}
s = new string(ch);
return s.Substring(0, idx);
}
// Driver code
public static void Main()
{
// initialise two strings
string s = "equ#ual";
string t = "gee##eeks";
if (removeBackspaces(s) == removeBackspaces(t))
Console.Write("True");
else
Console.Write("False");
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
/* Javascript implementation to Check if
two strings after processing
backspace character are equal or not*/
// function to compare the two strings
function removeBackspaces(s)
{
let n = s.length;
// To point at position after considering the
// backspaces
let idx = 0;
for (let i = 0; i < n; i++) {
if (s[i] != '#') {
s[idx] = s[i];
idx++;
}
else if (s[i] == '#' && idx >= 0) {
idx--;
}
// This idx can never point at negative index
// position
if (idx < 0)
idx = 0;
}
return s.substring(0, idx);
}
// Driver code
// initialise two strings
let s = "equ#ual";
let t = "gee##eeks";
if (removeBackspaces(s) == removeBackspaces(t))
console.log("True");
else
console.log("False");
// This code is contributed by poojaagarwal2.
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach: (Using Stack)
The idea is to use a stack that stores the last occurrence of a character other than "#" (i.e, Backspace) and iterate over the each given string and if we find any character other than '#' then we keep storing it into the stack otherwise remove the last occurred character which is store into the stack. Do the Similar process for both given strings and check if both strings are equal then print "Yes" otherwise "No".
Following is the implementation of the above approach:
C++
// C++ implementation to Check if
// two strings after processing
// backspace character are equal or not
#include <iostream>
#include <string>
using namespace std;
// function to remove backspaces and return refined string
string remove_backspace(string str) {
string res;
for (char c : str) {
if (c != '#') {
res.push_back(c);
} else if (!res.empty()) {
res.pop_back();
}
}
return res;
}
// function to compare the two strings
bool compare(string s, string t) {
s = remove_backspace(s);
t = remove_backspace(t);
return s == t;
}
// Driver code
int main() {
string s = "geee#e#ks";
string t = "gee##eeks";
if (compare(s, t)) {
cout << "True" << endl;
} else {
cout << "False" << endl;
}
return 0;
}
// This code is contributed by princekumaras
Java
// Java implementation to Check if
// two strings after processing
// backspace character are equal or not
import java.util.*;
public class BackspaceStringCompare {
// function to remove backspaces and return refined string
static String remove_backspace(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();
}
// function to compare the two strings
static boolean compare(String s, String t) {
s = remove_backspace(s);
t = remove_backspace(t);
return s.equals(t);
}
// Driver code
public static void main(String[] args) {
String s = "geee#e#ks";
String t = "gee##eeks";
if (compare(s, t)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
// This code is contributed by adityashatmfh
Python3
# Python implementation to Check if
# two strings after processing
# backspace character are equal or not
# function to compare the two strings
def compare(s, t):
# function to remove backspaces and return refined string
def remove_backspace(string):
a = []
for i in string:
if i != "#":
a.append(i)
else:
if len(a):
a.pop()
return "".join(a)
s, t = remove_backspace(s), remove_backspace(t) #remove backspaces from the strings
return s == t #return True if they are equal
# Driver code
# initialise two strings
s = "geee#e#ks"
t = "gee##eeks"
if (compare(s, t)):
print("True")
else:
print("False")
# This code is Contributed by Vivek Maddeshiya
C#
// C# implementation to Check if
// two strings after processing
// backspace character are equal or not
using System;
using System.Text;
public class BackspaceStringCompare {
// function to remove backspaces and return refined string
static string RemoveBackspace(string str) {
StringBuilder res = new StringBuilder();
foreach (char c in str) {
if (c != '#') {
res.Append(c);
} else if (res.Length > 0) {
res.Remove(res.Length - 1, 1);
}
}
return res.ToString();
}
// function to compare the two strings
static bool Compare(string s, string t) {
s = RemoveBackspace(s);
t = RemoveBackspace(t);
return s.Equals(t);
}
// Driver code
public static void Main(string[] args) {
string s = "geee#e#ks";
string t = "gee##eeks";
if (Compare(s, t)) {
Console.WriteLine("True");
} else {
Console.WriteLine("False");
}
}
}
// This code is contributed by codebraxnzt
JavaScript
// JavaScript program to check if two strings after processing
// backspace character are equal or not
// function to compare two strings
function compare(s, t){
// function to remove backspaces and return refined string
function remove_backspaces(string){
a = [];
for(let i = 0; i<string.length; i++){
if(string[i] != '#') a.push(string[i]);
else if(a.length > 0) a.pop();
}
return a.join("")
}
s = remove_backspaces(s);
t = remove_backspaces(t);
return s == t;
}
// driver program for above functions
let s = "geee#e#ks";
let t = "gee##eeks";
if(compare(s,t)) console.log("True");
else console.log("False");
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
Time Complexity: O(n), Where n is the length of the given string
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem