Reverse a String – Solution & Complexity

Solution Walkthrough

  1. Step 1: Understanding the Problem

    • The task is to reverse a given string s.
    • We cannot use built-in reverse functions or slicing, so we’ll use a two-pointer approach to reverse the string by swapping characters from each end.
  2. Step 2: Initialize Two Pointers

    • Set up two pointers: left starting at the beginning of the string (0) and right starting at the end (length - 1).
    • These pointers will move towards each other, swapping characters until they meet in the middle.
    def reverse_string(s: str) -> str:
        s = list(s)  # Convert string to list for in-place modification
        left, right = 0, len(s) - 1
        return left, right
  3. Step 3: Swap Characters Using a Third Variable

    • Inside a loop, swap the characters at left and right by storing one in a temporary variable.
    • After each swap, increment left and decrement right to move towards the center of the string.
    def reverse_string(s: str) -> str:
        s = list(s)  # Convert string to list for in-place modification
        left, right = 0, len(s) - 1
        while left < right:
            # Swap using a temporary variable
            temp = s[left]
            s[left] = s[right]
            s[right] = temp
            left += 1
            right -= 1
        return ''.join(s)  # Convert list back to string
  4. Step 4: Handle Edge Cases

    • Handle edge cases, including:
      • Empty strings, which should return an empty string.
      • Single-character strings, which should return the string itself.
      • Strings with spaces or special characters, which should be reversed as normal.
    def reverse_string(s: str) -> str:
        if len(s) <= 1:  # Handle empty or single-character strings
            return s
        s = list(s)
        left, right = 0, len(s) - 1
        while left < right:
            temp = s[left]
            s[left] = s[right]
            s[right] = temp
            left += 1
            right -= 1
        return ''.join(s)

FAQ