Reverse String
Receives a string of text and returns its characters in reverse order. It uses the classic two-pointer technique: one pointer starts at the beginning, the other at the end, and on each step they swap the characters they point to, then move one position toward each other. This continues until the pointers meet (an odd-length string leaves its middle character untouched) or cross (an even-length string has every character swapped). The whole string is reversed in place in O(n) time using only two extra variables. Returns a new string with the characters in reverse order; an empty or single-character string is returned unchanged.
Visualization
- Input
- Result
Algorithm code
// Reverse String — a single pure function. Reverses the character order of a
// string using the classic two-pointer swap: pointers start at both ends and
// walk inward, swapping the characters at each position until they meet or
// cross. No side effects.
/**
* @param {string} s - the string to reverse, e.g. "hello"
* @returns {string} the characters of s in reverse order, e.g. "olleh"
*/
export function reverseString(s) {
const chars = [...s];
let left = 0;
let right = chars.length - 1;
while (left < right) {
const temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left += 1;
right -= 1;
}
return chars.join("");
} FUNCTION reverseString(s):
chars ← characters of s
left ← 0
right ← length(chars) - 1
WHILE left < right:
temp ← chars[left]
chars[left] ← chars[right]
chars[right] ← temp
left ← left + 1
right ← right - 1
RETURN join(chars)