1 minute read

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.

Example 1:

Input: s = [“h”,”e”,”l”,”l”,”o”] Output: [“o”,”l”,”l”,”e”,”h”] Example 2:

Input: s = [“H”,”a”,”n”,”n”,”a”,”h”] Output: [“h”,”a”,”n”,”n”,”a”,”H”]

Constraints:

1 <= s.length <= 105 s[i] is a printable ascii character.

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function (s) {
  // Initialize two pointers 'left' and 'right' at the beginning and end of the string
  let left = 0;
  let right = s.length - 1;

  // Continue swapping characters until the 'left' pointer is greater than or equal to the 'right' pointer
  while (left < right) {
    // Swap characters at 'left' and 'right' positions using destructuring assignment
    [s[left], s[right]] = [s[right], s[left]];

    // Increment 'left' pointer and decrement 'right' pointer
    left++;
    right--;
  }
};

Time Complexity: The time complexity of the code is O(n), where n is the length of the string s. The algorithm iterates over half of the string, swapping characters at each iteration.

Space Complexity: The space complexity is O(1) since no additional space is used. The input string is modified in-place.

Leave a comment