Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Remove Occurrences Recursively

Delete every occurrence of one character with recursion. Students compare the first character, skip matches, and rebuild the remaining text in original order.

AdvancedPhase 3 - Level 4: String-based RecursionExample 6 of 10
remove-occurrences-recursively.py
1def remove_char(s, char_to_remove):
2 # Base case
3 if len(s) == 0:
4 return ""
5
6 # Check first character
7 if s[0] == char_to_remove:
8 return remove_char(s[1:], char_to_remove)
9 else:
10 return s[0] + remove_char(s[1:], char_to_remove)
11
12# Test
13text = input("Enter a string: ")
14char = input("Enter character to remove: ")
15result = remove_char(text, char)
16print(f"Result: {result}")

Output

Enter a string: Hello
Enter character to remove: l
Result: Heo

In this one

  • Skip exact matches
  • Keep nonmatching characters
  • Reduce by slicing

How it works

  1. 1

    Return empty text when s is empty.

  2. 2

    Omit the first character if it equals the removal target.

  3. 3

    Otherwise keep it before the processed suffix.

Edge cases

What happens if the target is absent?

What happens if the target is absent?

All original characters are kept.

What if every character matches?

What if every character matches?

The result is empty.

What's going on

remove_char works on the first character and recurses on s[1:]. A matching character contributes nothing; a nonmatch is kept before the processed suffix.

An empty string is the stopping result. Removing a from banana yields bnn. Matching is exact and case-sensitive, and a multi-character removal target does not match a single-character comparison. The slices and pending calls make this a teaching approach.

What happens if the target is absent? All original characters are kept.

What if every character matches? The result is empty.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which operation removes a matched character?

Pick an answer to check it.

Question 2

What happens if the target is absent?

Pick an answer to check it.

Questions people ask

What happens if the target is absent?

All original characters are kept.

What if every character matches?

The result is empty.

Which operation removes a matched character?

Returning only the processed suffix.