Reverse Field
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
- Tata Consultancy Services
Problem
An analyst reconciling a vendor export noticed every text field in it arrived written back to front. Restore a field s to its proper reading order, leaving a blank field blank.
Flip it. See what happens.
Example 1
Input:
s = "211-CDG"
Output:
"GDC-112"
Example 2
Input:
s = "tropxe"
Output:
"export"
Worked solution and explanation
What this warm-up is really checking
This is a type question dressed up as a data-cleaning chore. Everyone knows the field has to come back reversed. What separates people in the first two minutes is whether the thing they return is actually a str. Type reversed(s), see it run without an error, and you ship <reversed object at 0x...>, which equals nothing. Every case fails, the empty one included.
Step 1: Decide what type comes back
The grader compares your return value to strings like 'GDC-112'. So whatever reverses the characters has to finish by producing a str. In Python, reversed() hands you an iterator and list.reverse() hands you None. Neither one is the answer until you turn it back into a string.
Step 2: Let one rule cover the blank field
A blank field read back to front is still blank, and a one-character field reads the same either way. Pick a construct where both cases fall out for free. ''[::-1] is '' and 'Z'[::-1] is 'Z', so a guard clause here is just noise.
Step 3: Keep it linear
Any construct that builds the reversed str in one pass is the same skill: a slice, ''.join(reversed(s)), or a loop that collects characters and joins once at the end. What you want to avoid is result += ch inside a loop. Strings are immutable, so each append copies everything built so far.
def reverse_str(s: str) -> str:
return s[::-1]A step of -1 walks the field from last character to first and builds a new str.
- Runs, returns the wrong thing
return reversed(s)hands back an iterator.chars = list(s); return chars.reverse()hands backNone. Both pass a quick eyeball and fail every equality check.- Returns the field
return s[::-1]orreturn ''.join(reversed(s)). Each produces astrin O(n), and '' maps to '' with no extra branch.
Common follow-up questions
- How would you reverse the order of the words in a field while keeping each word readable? (Split on whitespace, reverse the list, rejoin; then discuss whether runs of multiple spaces must survive.)
- What changes when a field holds combining marks or emoji modifiers? (Grapheme clusters versus code points; `unicodedata` normalization only goes part of the way.)
- How would you restore a 10 GB field that does not fit in memory? (Read fixed-size chunks from the end, reverse each one, and take care not to split a multi-byte character at a chunk boundary.)