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

Two-pointer swap reversal
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 result

Common follow-up questions