Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if a string can become empty by recursively deleting a given sub-string in Python
Sometimes we need to check if a string can be completely emptied by repeatedly removing occurrences of a substring. This problem involves finding and removing a target substring until either the string becomes empty or no more occurrences exist.
So, if the input is like s = "pipipinnn" t = "pin", then the output will be True as we can remove "pin" from "pipipinnn", then we will get "pipinn", again remove "pin" to get string "pin", then remove it to make it empty.
Algorithm
To solve this, we will follow these steps:
- while size of s > 0, do
- position := starting index of t in s
- if position is not in the s, then
- come out from the loop
- s := remove t from s one time
- return true when size of s is same as 0 otherwise false
Example
Let us see the following implementation to get better understanding:
def solve(s, t):
while len(s) > 0:
position = s.find(t)
if position == -1:
break
s = s.replace(t, "", 1)
return len(s) == 0
s = "pipipinnn"
t = "pin"
print(solve(s, t))
The output of the above code is:
True
Step-by-Step Execution
Let's trace through the example to understand how it works:
def solve_with_trace(s, t):
step = 1
while len(s) > 0:
print(f"Step {step}: Current string = '{s}'")
position = s.find(t)
if position == -1:
print(f"'{t}' not found. Breaking.")
break
s = s.replace(t, "", 1)
print(f"After removing '{t}': '{s}'")
step += 1
result = len(s) == 0
print(f"Final result: {result}")
return result
s = "pipipinnn"
t = "pin"
solve_with_trace(s, t)
Step 1: Current string = 'pipipinnn' After removing 'pin': 'pipinn' Step 2: Current string = 'pipinn' After removing 'pin': 'pin' Step 3: Current string = 'pin' After removing 'pin': '' Final result: True
Alternative Approach Using Recursion
We can also solve this problem using recursion:
def solve_recursive(s, t):
if t not in s:
return len(s) == 0
return solve_recursive(s.replace(t, "", 1), t)
s = "pipipinnn"
t = "pin"
print(solve_recursive(s, t))
True
Edge Cases
Let's test some edge cases:
def test_edge_cases():
test_cases = [
("", "pin"), # Empty string
("pin", "pin"), # Exact match
("hello", "world"), # No match
("abcabc", "abc"), # Multiple occurrences
("abcdefg", "xyz") # Substring not present
]
for s, t in test_cases:
result = solve(s, t)
print(f"s='{s}', t='{t}' -> {result}")
test_edge_cases()
s='', t='pin' -> True s='pin', t='pin' -> True s='hello', t='world' -> False s='abcabc', t='abc' -> True s='abcdefg', t='xyz' -> False
Conclusion
The algorithm iteratively finds and removes the target substring until either the string becomes empty (return True) or no more occurrences exist (return False). Both iterative and recursive approaches work effectively for this problem.
