DEV Community

codingpineapple
codingpineapple

Posted on • Edited on

LeetCode 541. Reverse String II (Javascript solution)

Description:

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

var reverseStr = function(s, k) {
    // strings are immutable in javascript
    // converting to an array will allow in place letter swapping
    const a = s.split('');
    // loop through the array in 2*k increments
    for (let start = 0; start < a.length; start += 2 * k) {
        let i = start;
        let j = Math.min(start + k - 1, a.length - 1);
        // reverse first k characters in current increment
        while (i < j) {
            let tmp = a[i];
            a[i++] = a[j];
            a[j--] = tmp;
        }
    }
    // return a string as the result
    return a.join('');
};
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
tamb profile image
Tamb

What is k in this ?

Collapse
 
cod3pineapple profile image
codingpineapple

I posted the problem description. I think the solution will make more sense now.