Reverse String
EasySwap the ends, walk inward
Swap the first and last letters, then move inward — like flipping a word end to end.
The idea
Reverse in place with two pointers: swap the first and last characters, then move both toward the middle until they meet.
L
R
a
l
g
o
v
i
z
0
1
2
3
4
5
6
Step 1 of 5. Swap the ends and walk inward — reverses the string in place. Values: a, l, g, o, v, i, z. Pointers: L at index 0, R at index 6.
1/5
Optimal
timeO(n)spaceO(1)
In-place end swaps.
1// swap the ends, walk inward2let l = 0, r = s.length - 1;3while (l < r) {4 [s[l], s[r]] = [s[r], s[l]];5 l++; r--;6}7return s;Input
- array
- [a, l, g, o, v, i, z]
Memory
- L
- = 0 [a]
- R
- = 6 [z]
Output
- result
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- s = "hello"
- Output:
- "olleh"
- Explanation:
- Swap ends inward.
Example 2
- Input:
- s = "a"
- Output:
- "a"
- Explanation:
- One letter.
Example 3
- Input:
- s = "ab"
- Output:
- "ba"
- Explanation:
- Two letters swap.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.