The Mirror Image
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
- Allen Institute
Problem
Given a string s, return its reverse. Do not use slice reversal or reversed(); implement with a two-pointer or manual character-by-character approach.
Flip the tape backwards - start from the end.
Example 1
Input:
s = "hello"
Output:
"olleh"
Example 2
Input:
s = "abcde"
Output:
"edcba"
Worked solution and explanation
Why this problem exists in real interviews
This tests the two-pointer technique applied to string reversal. By prohibiting [::-1] and reversed(), interviewers force candidates to demonstrate understanding of in-place swapping mechanics.
Break down the requirements
Step 1: Convert string to a mutable list
Python strings are immutable, so convert to a list of characters to enable swapping.
Step 2: Set up two pointers at opposite ends
Pointer left starts at index 0, pointer right starts at the last index.
Step 3: Swap and move inward
Swap the characters at left and right, then increment left and decrement right. Stop when they meet.
Step 4: Join and return
Convert the list back to a string with ''.join().
The solution
def reverse_string(s):
chars = list(s)
left = 0
right = len(chars) - 1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
result = ''.join(chars)
return resultCommon follow-up questions
- How would you reverse only a substring from index i to j? (Tests applying the two-pointer technique to a bounded range.)
- What if you needed to reverse words but not characters? (Tests the 'reverse all, then reverse each word' pattern.)
- Can you do this without converting to a list? (Tests building the string from the end using concatenation or a list of characters appended in reverse order.)