Bird
Raised Fist0
DSA Pythonprogramming

String Reversal Approaches in DSA Python

Choose your learning style10 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.

Practice

(1/5)
1. Which of the following methods correctly reverses a string s in Python?
easy
A. Using reversed(s) without converting to string
B. Using slicing: s[::-1]
C. Using s.reverse() method
D. Using s.append() method

Solution

  1. Step 1: Understand string slicing

    The slicing syntax s[::-1] creates a new string with characters in reverse order.
  2. Step 2: Check other methods

    s.reverse() and s.append() are list methods, not valid for strings. reversed(s) returns an iterator, not a string, so it needs conversion.
  3. Final Answer:

    Using slicing: s[::-1] -> Option B
  4. Quick Check:

    String slicing with negative step reverses string [OK]
Hint: Use s[::-1] to reverse strings quickly [OK]
Common Mistakes:
  • Trying to use list methods on strings
  • Forgetting to convert reversed() iterator to string
  • Using append() on strings
2. Which of the following code snippets correctly reverses the string text = 'hello' and prints it?
easy
A. print(text.append('o'))
B. print(text.reverse())
C. print(text[::-2])
D. print(''.join(reversed(text)))

Solution

  1. Step 1: Analyze each option

    text.reverse() is invalid for strings. text[::-2] reverses with step 2, skipping characters. text.append() is invalid for strings.
  2. Step 2: Confirm correct syntax

    reversed(text) returns an iterator of characters reversed. ''.join() converts it back to string. This prints 'olleh'.
  3. Final Answer:

    print(''.join(reversed(text))) -> Option D
  4. Quick Check:

    reversed() + join() prints reversed string [OK]
Hint: Use ''.join(reversed(s)) to reverse strings [OK]
Common Mistakes:
  • Using reverse() method on strings
  • Using slicing with wrong step
  • Trying to append to strings
3. What is the output of the following code?
def reverse_string(s):
    result = ''
    for char in s:
        result = char + result
    return result

print(reverse_string('abc'))
medium
A. 'cba'
B. 'abc'
C. 'bac'
D. Error

Solution

  1. Step 1: Trace the loop for s='abc'

    Initially, result = ''. Iteration 1: char='a', result='a' + '' = 'a'. Iteration 2: char='b', result='b' + 'a' = 'ba'. Iteration 3: char='c', result='c' + 'ba' = 'cba'.
  2. Step 2: Return the reversed string

    The function returns 'cba', which is the reverse of 'abc'.
  3. Final Answer:

    'cba' -> Option A
  4. Quick Check:

    Prepending chars reverses string [OK]
Hint: Add each char before result to reverse string [OK]
Common Mistakes:
  • Appending char instead of prepending
  • Returning original string
  • Confusing order of concatenation
4. The following code is intended to reverse a string but has an error. What is the error?
def reverse_str(s):
    s.reverse()
    return s

print(reverse_str('hello'))
medium
A. Missing return statement
B. Function returns None
C. Strings do not have reverse() method
D. Syntax error in function definition

Solution

  1. Step 1: Check method usage on string

    The reverse() method exists for lists, not strings. Calling it on a string causes AttributeError.
  2. Step 2: Understand the error cause

    Since strings are immutable, they do not support reverse(). The code will raise an error at runtime.
  3. Final Answer:

    Strings do not have reverse() method -> Option C
  4. Quick Check:

    reverse() is list method, not string method [OK]
Hint: Use slicing or reversed() for strings, not reverse() [OK]
Common Mistakes:
  • Trying to use reverse() on strings
  • Expecting reverse() to modify string in place
  • Ignoring immutability of strings
5. You want to reverse only the vowels in a string s = 'hello world' while keeping other characters in place. Which approach below correctly achieves this?
hard
A. Extract vowels, reverse them, then replace vowels in original positions
B. Reverse entire string using s[::-1]
C. Use reversed(s) and join all characters
D. Replace vowels with '*' and then reverse string

Solution

  1. Step 1: Understand the problem

    We want to reverse only vowels, keeping consonants and spaces fixed in their places.
  2. Step 2: Analyze each option

    Reverse entire string using s[::-1] reverses whole string, changing all characters. Use reversed(s) and join all characters reverses all characters, not just vowels. Replace vowels with '*' and then reverse string replaces vowels with '*', losing original vowels. Extract vowels, reverse them, then replace vowels in original positions extracts vowels, reverses them, then puts them back in original vowel positions, preserving other characters.
  3. Final Answer:

    Extract vowels, reverse them, then replace vowels in original positions -> Option A
  4. Quick Check:

    Reverse vowels only by extracting and replacing [OK]
Hint: Extract vowels, reverse, then put back in place [OK]
Common Mistakes:
  • Reversing entire string instead of vowels only
  • Replacing vowels with placeholders without restoring
  • Ignoring character positions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard