Reverse String - Problem

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

Input & Output

Example 1 — Basic String
$ Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
💡 Note: Reverse the array in-place: swap h↔o, e↔l, middle l stays. Result: ["o","l","l","e","h"]
Example 2 — Even Length
$ Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
💡 Note: Even length array: swap H↔h, a↔a, n↔n. Result: ["h","a","n","n","a","H"]
Example 3 — Single Character
$ Input: s = ["A"]
Output: ["A"]
💡 Note: Single character array remains unchanged: ["A"]

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is a printable ascii character

Visualization

Tap to expand
Reverse String Problem: In-Place Array ReversalInput ArrayhelloTwo Pointers: Swap from both endsOutput ArrayollehConstraint: Modify array in-place with O(1) extra space✓ Time Complexity: O(n) | Space Complexity: O(1)Two pointers eliminate need for extra array - optimal solution!
Understanding the Visualization
1
Input Array
Character array: ["h","e","l","l","o"]
2
Reverse Process
Swap characters from both ends moving inward
3
Output Array
Reversed array: ["o","l","l","e","h"]
Key Takeaway
🎯 Key Insight: Two pointers from opposite ends swap characters while moving inward, achieving O(1) space reversal
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
125.0K Views
High Frequency
~8 min Avg. Time
4.3K 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