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 - Two Pointer Approach INPUT Character Array s[] "h" 0 "e" 1 "l" 2 "l" 3 "o" 4 left right Length: 5 Constraint: O(1) space Modify in-place ALGORITHM STEPS 1 Initialize Pointers left=0, right=len-1 2 While left < right Continue swapping 3 Swap Elements s[left] <--> s[right] 4 Move Pointers left++, right-- Swap Iterations: i=0: h <--> o [o,e,l,l,h] i=1: e <--> l [o,l,l,e,h] i=2: l == l done! Time: O(n) | Space: O(1) FINAL RESULT Reversed Array "o" 0 "l" 1 "l" 2 "e" 3 "h" 4 OK - Reversed! Output: ["o","l","l","e","h"] Total swaps: 2 Iterations: n/2 Key Insight: The Two-Pointer technique allows us to reverse the array in-place by swapping elements from both ends toward the center. This achieves O(n) time complexity with O(1) extra space - no additional array needed! TutorialsPoint - Reverse String | Two-Pointer Optimal Approach
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