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

Reverse String Words Recursively

Reverse word order with a recursive list helper. Students split whitespace, build the suffix result first, and join words without reversing letters inside them.

AdvancedPhase 3 - Level 4: String-based RecursionExample 10 of 10
reverse-string-words-recursively.py
1def reverse_words(words, index=0):
2 # Base case
3 if index >= len(words):
4 return ""
5
6 # Recurse first
7 result = reverse_words(words, index + 1)
8 # Add current word
9 if result:
10 return result + " " + words[index]
11 else:
12 return words[index]
13
14# Test
15text = input("Enter a string: ")
16words = text.split()
17result = reverse_words(words)
18print(f"Reversed words: {result}")

Output

Enter a string: Hello World Programming
Reversed words: Programming World Hello

In this one

  • Choose words as the unit
  • Reverse through suffix returns
  • Control join separators

How it works

  1. 1

    Split input into whitespace-delimited words.

  2. 2

    Recursively build the later words first.

  3. 3

    Append the current word with a separator only if needed.

Edge cases

What if the input is only spaces?

What if the input is only spaces?

split gives an empty list and the result is empty.

Are letters inside each word reversed?

Are letters inside each word reversed?

No. Only the order of whole words changes.

What's going on

split creates the words before recursion begins. The helper processes later words first, then adds the current word after that returned result.

The empty suffix needs special handling to avoid a leading separator. For red blue green, the result is green blue red. Character order inside each word stays unchanged. split without arguments collapses whitespace, so original spacing is not preserved.

What if the input is only spaces? split gives an empty list and the result is empty.

Are letters inside each word reversed? No. Only the order of whole words changes.

Quiz

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

Question 1

Why check if result is nonempty?

Pick an answer to check it.

Question 2

What if the input is only spaces?

Pick an answer to check it.

Questions people ask

What if the input is only spaces?

split gives an empty list and the result is empty.

Are letters inside each word reversed?

No. Only the order of whole words changes.

Why check if result is nonempty?

To avoid an unwanted separator at the start.