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:
1 <= s.length <= 10⁵s[i]is a printable ascii character.
Approach: Two-Pointer Technique
func reverseString(s []byte) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}Intuition
The idea is to use two pointers—one starting at the beginning and the other at the end of the string—and swap the characters at these pointers. By moving both pointers towards the center, the entire string is reversed in place.
Algorithm
- Initialize Two Pointers:
Set pointeriat the beginning (index 0) and pointerjat the end (indexlen(s)-1) of the byte slice. - Swap Characters:
Whilei < j, swap the characterss[i]ands[j]. - Move Pointers:
Incrementiand decrementjafter each swap. - Stop Condition:
Continue this process untiliis no longer less thanj.
Complexity Analysis
-
Time Complexity:
O(n)– The algorithm performs a single pass through half of the string, which is linear relative to the length of the string. -
Space Complexity:
O(1)– The reversal is done in-place without using additional data structures.
Wrap up
If you found this guide helpful, consider subscribing to my newsletter on jyotirmoy.dev/blogs , You can also follow me on Twitter jyotirmoydotdev for updates and more content.

