DEV Community


Posted on • Updated on

LeetCode 541. Reverse String II (Javascript solution)


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)

tamb profile image

What is k in this ?

cod3pineapple profile image

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