Check if a string can become empty by recursive deletion using Slicing (original) (raw)

Last Updated : 11 Dec, 2025

Given a string 'S' and a substring 'sub', the task is to determine whether 'S' can be reduced to an empty string by repeatedly deleting one occurrence at a time of the substring 'sub' whenever it appears in the string.

**Example:

**Input:
s = "aaaaaa"
sub = "aa"

**Output:
True (string becomes empty)

**Explanation:
"aaaaaa" → remove "aa" → "aaaa"
"aaaa" → remove "aa" → "aa"
"aa" → remove "aa" → ""

While-loop with slicing

This method keeps checking if the substring exists in the main string, and whenever it does, we remove it using slicing. The loop continues until no more removals are possible, and then we check if the string is empty.

Python `

s = "geeksforgeeks" sub = "geeks"

while True: ind = s.find(sub)
if ind == -1:
break s = s[:ind] + s[ind + len(sub):]

res = (s == "") print(res)

`

**Explanation:

Recursive Deletion Using Slicing

Recursive deletion using slicing means removing a substring from a string again and again by cutting it out using slicing (s[: ]). The process keeps calling itself until either the string becomes empty or no more deletions are possible.

Python `

def fun(s, sub):

if not s:
    return True

ind = s.find(sub)

if ind != -1:
    s1 = s[:ind] + s[ind + len(sub):]
    return fun(s1, sub)
return False

s = "geeksforgeeks" sub = "geeks"

res = fun(s, sub) print(res)

`

**Explanation:

Using replace() Recursively

This method removes the substring using replace() inside a recursive function. Each recursive call removes the substring again and again until either the string becomes empty or no more removals are possible.

Python `

def fun(s, sub): if not s:
return True s1 = s.replace(sub, "")

if s1 == s:           
    return False
return fun(s1, sub)   

s = "geeksforgeeks" sub = "geeks" res = fun(s, sub) print(res)

`

**Explanation:

Iterative replace() Loop

An iterative replace() loop repeatedly calls replace() inside a loop to update a string step-by-step until all desired changes are applied.

Python `

s = "geeksforgeeks" sub = "geeks"

prev = None while s != prev: prev = s s = s.replace(sub, "")

print(s == "")

`

**Explanation: