Reverse String - Problem
The Challenge: You're given a string as an array of characters and need to reverse it in-place. This means you must modify the original array without creating a new one, using only O(1) extra memory space.

What you get: An array of characters like ['h','e','l','l','o']
What you return: The same array, but reversed: ['o','l','l','e','h']

This is a fundamental string manipulation problem that tests your understanding of array indexing and space-efficient algorithms. The constraint of in-place modification makes it more challenging than simply creating a new reversed string.

Input & Output

example_1.py โ€” Basic String
$ Input: s = ['h','e','l','l','o']
โ€บ Output: ['o','l','l','e','h']
๐Ÿ’ก Note: We reverse the string 'hello' by swapping characters from both ends moving inward. First swap hโ†”o, then eโ†”l, leaving the middle 'l' unchanged.
example_2.py โ€” Even Length
$ Input: s = ['H','a','n','n','a','h']
โ€บ Output: ['h','a','n','n','a','H']
๐Ÿ’ก Note: For even-length strings, we swap all pairs: Hโ†”h, aโ†”a, nโ†”n. Each character finds its mirror position.
example_3.py โ€” Single Character
$ Input: s = ['A']
โ€บ Output: ['A']
๐Ÿ’ก Note: Edge case: A single character string remains unchanged since there are no other characters to swap with.

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s[i] is a printable ASCII character
  • Must modify the input array in-place with O(1) extra memory

Visualization

Tap to expand
Two-Pointer String Reversal AnimationStage 1: SetupHELLOLEFTRIGHTStage 2: First Swap (H โ†” O)OELLHLEFTRIGHTStage 3: Second Swap (E โ†” L)OLLEHโœ“ Pointers meet - DONE!๐Ÿ’ก Key Insights:โ€ข Only swap n/2 timesโ€ข No extra memory neededโ€ข Pointers prevent overwritesโ€ข Works for any string length
Understanding the Visualization
1
Place Pointers
Position left pointer at start (index 0) and right pointer at end (index n-1)
2
Swap & Move
Swap characters at pointer positions, then move left pointer right and right pointer left
3
Meet in Middle
Continue until pointers meet or cross - the string is now reversed!
Key Takeaway
๐ŸŽฏ Key Insight: By using two pointers that converge toward the center, we can reverse any string in-place with optimal space efficiency, requiring only constant extra memory regardless of input size.
Asked in
Google 25 Amazon 20 Meta 15 Microsoft 18
125.0K Views
High Frequency
~10 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen