Check if a string can become empty by recursively deleting a given sub-string
Last Updated :
20 Mar, 2023
Given a string "str" and another string "sub_str". We are allowed to delete "sub_str" from "str" any number of times. It is also given that the "sub_str" appears only once at a time. The task is to find if "str" can become empty by removing "sub_str" again and again.
Examples:
Input : str = "GEEGEEKSKS", sub_str = "GEEKS"
Output : Yes
Explanation : In the string GEEGEEKSKS, we can first
delete the substring GEEKS from position 4.
The new string now becomes GEEKS. We can
again delete sub-string GEEKS from position 1.
Now the string becomes empty.
Input : str = "GEEGEEKSSGEK", sub_str = "GEEKS"
Output : No
Explanation : In the string it is not possible to make the
string empty in any possible manner.
Method#1: A simple solution to solve this problem is by using inbuilt string functions find() and erase(). First input the sub-string substr for searching purpose in the original string str, then iterate the original string to find the index of the sub-string using find() which return starting index of the sub-string in the original string else -1 if not found and erase that sub-string using erase() until the length of the original string is greater than 0.
The above simple solutions work because the given substring appears only once at a time.
C++
// C++ Program to check if a string can be
// converted to an empty string by deleting
// given sub-string from any position, any
// number of times.
#include<bits/stdc++.h>
using namespace std;
// Returns true if str can be made empty by
// recursively removing sub_str.
bool canBecomeEmpty(string str, string sub_str)
{
while (str.size() > 0)
{
// idx: to store starting index of sub-
// string found in the original string
int idx = str.find(sub_str);
if (idx == -1)
break;
// Erasing the found sub-string from
// the original string
str.erase(idx, sub_str.size());
}
return (str.size() == 0);
}
// Driver code
int main()
{
string str = "GEEGEEKSKS", sub_str = "GEEKS";
if (canBecomeEmpty(str, sub_str))
cout<<"\nYes";
else
cout<<"\nNo";
return 0;
}
Java
//Java program to check if a string can be
// converted to an empty string by deleting
// given sub-string from any position, any
// number of times.
class GFG {
// Returns true if str can be made empty by
// recursively removing sub_str.
static boolean canBecomeEmpty(String str, String sub_str) {
while (str.length() > 0) {
// idx: to store starting index of sub-
// string found in the original string
int idx = str.indexOf(sub_str);
if (idx == -1) {
break;
}
// Erasing the found sub-string from
// the original string
str = str.replaceFirst(sub_str,"");
}
return (str.length() == 0);
}
// Driver code
public static void main(String[] args) {
String str = "GEEGEEKSKS", sub_str = "GEEKS";
if (canBecomeEmpty(str, sub_str)) {
System.out.print("\nYes");
} else {
System.out.print("\nNo");
}
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to check if a string can be
# converted to an empty string by deleting
# given sub-string from any position, any
# number of times.
# Returns true if str can be made empty by
# recursively removing sub_str.
def canBecomeEmpty(string, sub_str):
while len(string) > 0:
# idx: to store starting index of sub-
# string found in the original string
idx = string.find(sub_str)
if idx == -1:
break
# Erasing the found sub-string from
# the original string
string = string.replace(sub_str, "", 1)
return (len(string) == 0)
# Driver code
if __name__ == "__main__":
string = "GEEGEEKSKS"
sub_str = "GEEKS"
if canBecomeEmpty(string, sub_str):
print("Yes")
else:
print("No")
# This code is contributed by
# sanjeev2552
C#
// C# program to check if a string can be
// converted to an empty string by deleting
// given sub-string from any position, any
// number of times.
using System;
class GFG
{
// Returns true if str can be made empty by
// recursively removing sub_str.
static Boolean canBecomeEmpty(String str, String sub_str)
{
while (str.Length > 0)
{
// idx: to store starting index of sub-
// string found in the original string
int idx = str.IndexOf(sub_str);
if (idx == -1)
{
break;
}
// Erasing the found sub-string from
// the original string
str = str.Replace(sub_str,"");
}
return (str.Length == 0);
}
// Driver code
public static void Main(String[] args)
{
String str = "GEEGEEKSKS", sub_str = "GEEKS";
if (canBecomeEmpty(str, sub_str))
{
Console.Write("\nYes");
}
else
{
Console.Write("\nNo");
}
}
}
// This code is contributed by 29AjayKumar
JavaScript
// JS Code to Check if a string can become empty by
// recursively deleting a given sub-string
function canBecomeEmpty(str, sub_str) {
while (str.length > 0) {
// idx: to store starting index of sub-
// string found in the original string
let idx = str.indexOf(sub_str);
if (idx == -1)
break;
// Erasing the found sub-string from
// the original string
str = str.slice(0, idx) + str.slice(idx + sub_str.length);
}
return (str.length == 0);
}
// Driver code
let str = "GEEGEEKSKS", sub_str = "GEEKS";
if (canBecomeEmpty(str, sub_str))
console.log("Yes");
else
console.log("No");
Time Complexity: O(N^2)
Auxiliary Space: O(N+M), where N is the length of the string and M is the length of sub-string.
Method#2: One possible solution would be to use the regular expression. Regular expressions modules are very helpful with string. The regular expression module has a search function that is used to find the patterns in the string. And replace function is used for replacing the characters of string.
Follow are the steps for our approach:
- Use the re.search function on a string to find the pattern in a string.
- Use the re.replace function to replace the sub-string from a string.
- Repeat steps one and two until there is a sub-string in the string after replacing it.
- At last if the string is empty after all replacing then it can become empty else it cannot become empty.
Example
C++
// C++ Program to check if a string can be
// converted to an empty string by deleting
// given sub-string from any position, any
// number of times.
#include <bits/stdc++.h>
using namespace std;
// Returns true if str can be made empty by
// recursively removing sub_str.
bool canBecomeEmpty(string str1, string sub_str)
{
regex r(sub_str);
smatch m;
// matches words beginning by "Geek"
while (regex_search(str1, m, r)) {
// regex_replace() for replacing the match with
// 'geek'
str1 = regex_replace(str1, r, "");
}
// Returning result
return true ? str1 == "" : false;
}
// Driver code
int main()
{
string s = "GeeksForGeeGeeksks";
string k = "Geeks";
if (canBecomeEmpty(s, k)) {
cout << "\nYes";
}
else {
cout << "\nNo";
}
return 0;
}
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
// Returns true if str can be made empty by
// recursively removing sub_str.
static boolean canBecomeEmpty(String str1, String sub_str){
Pattern r = Pattern.compile(sub_str);
Matcher m;
while((m = r.matcher(str1)).find()){
// replaceAll() for replacing the match with ""
str1 = m.replaceAll("");
}
// Returning result
return str1.equals("");
}
// Driver code
public static void main(String[] args) {
String s = "GeeksForGeeGeeksks";
String k = "Geeks";
if (canBecomeEmpty(s, k)){
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
Python3
# Python3 program to check if a string can be
# converted to an empty string by deleting
# given sub-string from any position, any
# number of times.
# Returns true if str can be made empty by
# recursively removing sub_str.
import re
def canBecomeEmpty(string, sub_str):
# finding sub-string in string
while sub_str in string :
# Replacing sub-string from string
string = re.sub(sub_str, "", string)
# Returning result
return True if string == "" else False
# Driver code
if __name__ == "__main__":
string = "GeeksforGeeGeeksks"
sub_str = "Geeks"
if canBecomeEmpty(string, sub_str):
print("Yes")
else:
print("No")
# This code is contributed by
# sanjeev2552
C#
// C# implementation
using System;
using System.Text.RegularExpressions;
public class Program
{
// Returns true if str can be made empty by
// recursively removing sub_str.
static bool CanBecomeEmpty(string str1, string sub_str)
{
Regex r = new Regex(sub_str);
// matches words beginning by "Geek"
Match m;
while (r.IsMatch(str1))
{
// Replace() for replacing the match with 'geek'
str1 = r.Replace(str1, "");
}
// Returning result
return str1 == "" ? true : false;
}
// Driver code
public static void Main()
{
string s = "GeeksForGeeGeeksks";
string k = "Geeks";
if (CanBecomeEmpty(s, k))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
JavaScript
// Javascript program to check if a string can be
// converted to an empty string by deleting
// given sub-string from any position, any
// number of times.
// Returns true if str can be made empty by
// recursively removing sub_str
function canBecomeEmpty(str,sub_str)
{
// Regular expression for sub_string
const regex = new RegExp(sub_str);
// Iterating over string until it matches sub_string
while(regex.test(str)){
// Replacing sub-string from string
str = str.replace(regex, '')
}
// Returning result
return false ? str : true ;
}
// Driver code
let str = "GeeksForGeeGeeksks", sub_str = "Geeks";
if (canBecomeEmpty(str, sub_str)) {
console.log("Yes");
} else {
console.log("No");
}
// This code is contributed by sam snehil
Similar Reads
Check if a string can become empty by recursive deletion using Slicing To check if the string "geeksforgeeks" can become empty by recursively deleting occurrences of a specific substring, we can use string slicing and recursion. Here's how to do it for the string "geeksforgeeks" with a specific substring, say "geeks".Let's understand this with the help of an example:Py
2 min read
Check if a string consisting only of a, b, c can be made empty by removing substring "abc" recursively Given a string S size of N consisting of characters 'a', 'b', and 'c' only, the task is to check if the given string can be made empty by removing the string "abc" recursively or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = abcabcOutput: YesExplanation:Belo
7 min read
Check if a string can be converted to another given string by removal of a substring Given two strings S and T of length N and M respectively, the task is to check if the string S can be converted to the string T by removing at most one substring of the string S. If found to be true, then print âYESâ. Otherwise, print âNOâ. Example: Input: S = âabcdefâ, T = âabcâ Output: YES Explana
7 min read
Count of ways to empty given String by recursively removing all adjacent duplicates Given a string S, in one move it is allowed to remove two adjacent equal characters. After the removal, both endpoints of the removed characters are joined. Calculate the total number of ways to empty the string. Example: Input: S = aabccbOutput: 3Explanation:1. aabccb -> aabb -> aa 2. aabccb
9 min read
Check if a string can be made empty by repeatedly removing given subsequence Given a string str containing characters 'G' and 'F' only, the task is to check if the given string str can be made empty after removing all subsequences of the form "GFG". Examples: Input : N = 6, str[] = "GFGFGG"Output : YesExplanation : Two strings of "GFG" can be made with the first one with ind
7 min read