NeetCode #176LC-344EasyTwo PointersNC 250
← Back to All Problems

#176 · #344 · Reverse String(反转字符串)

📌 Problem Statement & Constraints

Write a function that reverses a character array s in place. You must do it with O(1) extra memory. Constraints: 1 <= s.length <= 10^5; s[i] is a printable ASCII character.

💡 Core Algorithmic Approaches

  1. Use two pointers at the ends and swap the characters they point to.
  2. After each swap, move both pointers inward by one.
  3. Stop when the pointers meet or cross, which handles both odd and even lengths uniformly.
  4. This is the canonical in-place two-pointer exercise.

💻 Benchmark Python3 Implementation

class Solution:
    def reverseString(self, s: List[str]) -> None:
        i, j = 0, len(s) - 1
        while i < j:
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): n/2 swaps.
💾 Space Complexity
O(1): in place.

⚠️ Interview Pitfalls & Follow-ups

  • Using s.reverse() or s[::-1]: correct for the result but the first is a library call and the second allocates a new list, which the O(1) requirement forbids.
  • Looping for i in range(len(s) // 2) with an off-by-one: the boundary is len(s) // 2, exclusive.
  • Returning the array: the signature returns None; the reversal is in place.
  • Swapping with a temporary variable incorrectly: Python's tuple assignment handles it atomically.