Open In App

Check if a string can become empty by recursive deletion using Slicing

Last Updated : 03 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

def can_become_empty_with_slicing(string, substring):
  
    # If the string is empty, it can be considered successfully reduced to empty
    if not string:
        return True
    
    # Check if the substring exists at any position
    index = string.find(substring)
    if index != -1:
        # Remove the substring using slicing and recursively check
        return can_become_empty_with_slicing(string[:index] + string[index + len(substring):], substring)
    
    # If the substring is not found, and the string is not empty, return False
    return False

# Example test case
input_string = "geeksforgeeks"
substring = "geeks"

# Call the function and store the result
result = can_become_empty_with_slicing(input_string, substring)

print(result)

Output
False

Explanation:

  1. Base case: If the string becomes empty (i.e., not string), the function returns True, indicating that the string has successfully been reduced to an empty string.
  2. Recursive case: The function checks if the substring "geeks" exists in the string. If it does, it removes the first occurrence of the substring and recursively calls itself with the modified string.
  3. If the substring isn’t found, the function returns False, indicating the string can’t be reduced to empty by removing the substring.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg