# The Word Flipper

> The sentence stays, the words surrender.

Canonical URL: <https://datadriven.io/problems/the_word_flipper>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a sentence with single-space-separated words, return the sentence with word order reversed. ('hello world' -> 'world hello')

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **string splitting and rejoining**, a basic but important string manipulation pattern. It probes whether a candidate can reverse word order without reversing the characters within each word.

---

### Break down the requirements

#### Step 1: Split the sentence into words

Use `.split()` or `.split(' ')` to break on spaces.

#### Step 2: Reverse the word list

Reverse the order of the list elements, not the characters.

#### Step 3: Rejoin with spaces

Use `' '.join()` to reconstruct the sentence.

---

### The solution

**Split, reverse iteration, rejoin**

```python
def reverse_words(sentence: str) -> str:
    words = sentence.split()
    reversed_words = []
    for i in range(len(words) - 1, -1, -1):
        reversed_words.append(words[i])
    result = " ".join(reversed_words)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the length of the sentence.
> 
> **Space:** O(n) for the word list and result string.

> **Interviewers Watch For**
>
> Handling multiple spaces correctly. `split()` without arguments handles multiple spaces and strips leading/trailing whitespace. `split(' ')` preserves empty strings between multiple spaces.

> **Common Pitfall**
>
> Reversing the entire string instead of just the word order. `'hello world'` reversed character-by-character is `'dlrow olleh'`, not `'world hello'`.

---

## Common follow-up questions

- Can you do this in-place without split? _(Tests the two-pass approach: reverse the entire string, then reverse each word individually.)_
- What if the sentence has leading/trailing/multiple spaces? _(Tests normalizing whitespace while preserving the reversal.)_
- What about preserving punctuation positions? _(Tests more complex parsing where punctuation stays attached to its word.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_word_flipper)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.