The Mirror Words
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
- Tenet Healthcare
Problem
We're cleaning up a line of space-separated text where each word needs its letters flipped end to end. Return the line with every word reversed but left in its original position.
Each word looks back at itself.
Example 1
Input:
sentence = "hello world"
Output:
"olleh dlrow"
Example 2
Input:
sentence = "data engineer"
Output:
"atad reenigne"
Worked solution and explanation
What this problem is really testing
Strip the costume and this is a split, transform, rejoin drill wearing a one-word disguise. The trap is right there in the word 'reverse': reach for sentence[::-1] on the whole string and you flip the letters AND the word order in one move, so 'hello world' comes back 'dlrow olleh' instead of 'olleh dlrow'. What the interviewer is watching is whether you turn each word's letters around WITHOUT touching the sentence's structure: split on the space, reverse each piece on its own, glue them back with the same single spaces.
Getting there
Step 1: Cut on the space, exactly
Split on a literal single space with split(' '), not the bare split(). The bare version collapses runs of whitespace and drops empties, which quietly rewrites your separators; the literal-space split keeps the structure one-to-one so the rejoin is exact.
Step 2: Reverse each word on its own
Flip each word with a slice, word[::-1]. This is the whole job scoped down to a single token, so the word-order question never even comes up: you are only ever looking at one word at a time.
Step 3: Glue it back
Join the flipped words back with a single space. Because you split on ' ' and join on ' ', the separators you emit are the separators you were handed.
The solution
def reverse_each_word(sentence):
return ' '.join(word[::-1] for word in sentence.split(' '))One pass over the words: split on the space, reverse each with a slice, join back on the space.
- Whole-string reverse (wrong)
- sentence[::-1] on 'hello world' returns 'dlrow olleh'. The letters are reversed, but so is the word order: the structure got dragged along with the content.
- Per-word reverse (right)
- Split first, then reverse each word, and 'hello world' returns 'olleh dlrow'. The words hold their positions; only the letters inside each one turn around.
Common follow-up questions
- What if the sentence had multiple consecutive spaces between words? (Tests whether split behavior changes and how to preserve spacing across runs of whitespace.)
- How would you reverse the order of the words instead of the letters inside them? (Tests the complementary problem: split, reverse the list of words, rejoin.)
- Could you do this in place on a mutable character array? (Tests the classic two-step in-place trick: reverse the whole array, then reverse each word span.)