DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

Reverse String

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
};

Top comments (0)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: