The Word Flipper

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Ripple

Problem

We're tidying up short text records, each held in sentence as words separated by single spaces. Return the same text with the order of the words flipped.

The sentence stays, the words surrender.

Example 1

Input:

sentence = "hello world"

Output:

"world hello"

Example 2

Input:

sentence = "the quick brown fox"

Output:

"fox brown quick the"

Worked solution and explanation

What this really is

This is a tokenize-reverse-rejoin dressed up as text cleanup, and the whole thing lives or dies on one decision: what you reverse. The skill being probed is whether you reverse the *sequence of words* while leaving each word's spelling alone. Almost everyone knows [::-1]. The tell is whether you reach for it on the raw string or on the list of words. Point it at the string and 'hello world' comes back 'dlrow olleh': every word spelled backwards, nothing matches.


How to get there

Step 1: Break the sentence into words

sentence.split() gives you a list of the words. It splits on whitespace, so the clean single spaces the inputs use fall away cleanly and you're left with just the tokens.

Step 2: Reverse the word list, not the string

Now [::-1] does exactly what you want: it reverses the list order without touching the strings inside it. This is the one place the slice belongs.

Step 3: Rejoin with a single space

' '.join(...) stitches the reversed words back into a sentence with a single space between them, matching the input's spacing.


The solution

Split, reverse the list, rejoin
def reverse_words(sentence):
    return " ".join(sentence.split()[::-1])

One pass to split, one to reverse, one to join: O(n) in the length of the sentence.


Common follow-up questions