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

Remove Spaces Recursively

Remove ordinary spaces recursively from text. Students choose whether to keep the first character and distinguish a literal space from every whitespace character.

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

Output

Enter a string: Hello World
Without spaces: HelloWorld

In this one

  • Filter through recursive returns
  • Match literal spaces
  • Preserve kept character order

How it works

  1. 1

    Return empty text at an empty suffix.

  2. 2

    If the first character is a space, skip it.

  3. 3

    Otherwise prepend it to the processed suffix.

Edge cases

Are tabs removed?

Are tabs removed?

No. Only an ordinary space matches the condition.

What if every character is a space?

What if every character is a space?

The final result is empty.

What's going on

An empty string ends recursion. For a leading ordinary space, the function returns only the processed suffix; otherwise it keeps s[0] before that suffix.

For a b, the returned text is ab. Character order is preserved because kept characters are joined before the suffix result. Tabs and other whitespace are not the literal ' ' tested here, so they remain. Calls and slices use memory.

Are tabs removed? No. Only an ordinary space matches the condition.

What if every character is a space? The final result is empty.

Quiz

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

Question 1

Which branch keeps a character?

Pick an answer to check it.

Question 2

Are tabs removed?

Pick an answer to check it.

Questions people ask

Are tabs removed?

No. Only an ordinary space matches the condition.

What if every character is a space?

The final result is empty.

Which branch keeps a character?

The nonspace branch.