0
0
DSA Pythonprogramming

String Reversal Approaches in DSA Python

Choose your learning style9 modes available
Mental Model
Reversing a string means flipping its characters so the last becomes first and the first becomes last.
Analogy: Imagine reading a sentence backwards, starting from the end and moving to the beginning, like rewinding a tape.
Original: H -> e -> l -> l -> o -> null
Reversed: o -> l -> l -> e -> H -> null
Dry Run Walkthrough
Input: string: 'hello'
Goal: Reverse the string so it reads 'olleh'
Step 1: Start with two pointers: left at 'h' (index 0), right at 'o' (index 4)
h [left] -> e -> l -> l -> o [right] -> null
Why: We need to swap characters from both ends moving inward
Step 2: Swap characters at left and right: 'h' and 'o'
o -> e -> l -> l -> h
Why: Swapping first and last characters moves them to correct reversed positions
Step 3: Move left pointer to 'e' (index 1), right pointer to 'l' (index 3)
o -> e [left] -> l -> l [right] -> h
Why: Continue swapping inward to reverse the middle characters
Step 4: Swap characters at left and right: 'e' and 'l'
o -> l -> l -> e -> h
Why: Swapping these moves the middle characters to their reversed positions
Step 5: Move left pointer to 'l' (index 2), right pointer to 'l' (index 2), pointers meet
o -> l -> l [left,right] -> e -> h
Why: Pointers meet or cross, so reversal is complete
Result:
o -> l -> l -> e -> h
Reversed string: 'olleh'
Annotated Code
DSA Python
class StringReverser:
    def reverse_in_place(self, s: list[str]) -> None:
        left, right = 0, len(s) - 1
        while left < right:
            s[left], s[right] = s[right], s[left]  # swap characters
            left += 1  # move left pointer right
            right -= 1  # move right pointer left

    def reverse_new_string(self, s: str) -> str:
        result = []
        for i in range(len(s) - 1, -1, -1):
            result.append(s[i])  # add characters from end to start
        return ''.join(result)


if __name__ == '__main__':
    original = 'hello'

    # Approach 1: In-place reversal using list
    s_list = list(original)
    reverser = StringReverser()
    reverser.reverse_in_place(s_list)
    print(''.join(s_list))

    # Approach 2: Create new reversed string
    reversed_str = reverser.reverse_new_string(original)
    print(reversed_str)
while left < right:
loop until pointers meet or cross to reverse all pairs
s[left], s[right] = s[right], s[left] # swap characters
swap characters at left and right pointers
left += 1 # move left pointer right
advance left pointer inward
right -= 1 # move right pointer left
advance right pointer inward
for i in range(len(s) - 1, -1, -1):
iterate string indices backward to build reversed string
result.append(s[i]) # add characters from end to start
append characters in reverse order
OutputSuccess
olleh olleh
Complexity Analysis
Time: O(n) because each character is visited once during reversal
Space: O(1) for in-place reversal, O(n) for new string approach due to extra storage
vs Alternative: In-place reversal saves space compared to creating a new reversed string which uses extra memory
Edge Cases
empty string
returns empty string immediately without errors
DSA Python
while left < right:
single character string
string remains the same as reversal of one char is itself
DSA Python
while left < right:
string with repeated characters
reverses correctly preserving duplicates
DSA Python
s[left], s[right] = s[right], s[left]  # swap characters
When to Use This Pattern
When you need to reverse a sequence of characters, use two-pointer swapping or build a new reversed sequence to efficiently reverse strings.
Common Mistakes
Mistake: Swapping characters without moving pointers inward causes infinite loop
Fix: Always move left pointer right and right pointer left after swapping
Mistake: Trying to reverse immutable string directly without converting to list
Fix: Convert string to list before in-place reversal or build a new string
Summary
Reverses a string by swapping characters from both ends or building a new reversed string.
Use when you need the characters in reverse order for algorithms or display.
The key insight is using two pointers moving inward to swap characters efficiently.