DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay