Write a function that reverses a string. The input string is given as an array of characters char[] .

Conditions:

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: [“h”,“e”,“l”,“l”,“o”]

Output: [“o”,“l”,“l”,“e”,“h”]

Alogrithm:

  1. Loop through the half of the array
  2. swap elements
  3. profit :-)

Code

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
	let mid = Math.floor(s.length / 2);
	for (let i = 0; i < mid; i++) {
		// Basic Swapping
		let temp = s[i];
		s[i] = s[s.length - i - 1];
		s[s.length - i - 1] = temp;
	}
	return s
};

Alternative Approach

instead of using for loop, you can use pointers

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
	let left = 0, right = s.length - 1;

	while (left < right) {
		let temp = s[right];
		s[right--] = s[left];
		s[left++] = temp;
	}
	return s
};

This post is also available on DEV.