AAlgoLoopSpaced repetition for LeetCode
EASYTwo PointersLeetCode ↗

Reverse String

The key idea

Reversing in place is just mirroring the array around its center. Put one pointer left at the start and another right at the end, swap the two characters, then step left forward and right backward. When they meet or cross, every pair has been flipped and the array is reversed using only the two index variables for extra memory.

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.

Constraints

Examples

Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Input: s = ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Two Pointers problems