Reverse string in alternating chunks of size k

Viewed 925

Given a string and an integer k, you need to reverse the first k characters for every segment of length 2k characters counting from the start of the string. If there are less 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.

Example

Input:  s = "abcdefg", k = 2
Output: "bacdfeg"

In the above example, the first chunk of two "ab" was reversed to "ba" and the third chunk of two "ef" was reversed to "fe".

This is my approach:

var reverseStr = function(s, k) {
  for (let i = 0; i < k; i++) {
    let temp = s[i];
    s[i] = s[k - i - 1];
    s[k - i - 1] = temp
  }
  return s
};

console.log(reverseStr("abcdefg", 2))

How do I produce the desired output?

4 Answers

One option is to use a regular expression to match up to k characters, followed by up to 2k characters - then use a replacer function to reverse only the initial k characters:

var reverseStr = function(s, k) {
  const pattern = new RegExp(`(.{1,${k}})(.{0,${k}})`, 'g');
  return s.replace(pattern, (_, g1, g2) => [...g1].reverse().join('') + g2);
};

console.log(reverseStr("abcdefg", 2))

Strings in JavaScript are immutable, you can't assign to their indexes to modify the string in place. You need to build a new string and return it.

You need a loop for each 2k group. Extract that substring, reverse the first k characters, then concatenate them to the result.

function reverseStr(s, k) {
  let result = "";
  for (let i = 0; i < s.length; i += 2*k) {
    let chunk1 = s.substr(i, k);
    // reverse first half
    chunk1 = chunk1.split("").reverse().join("");
    let chunk2 = s.substr(i+k, k);
    result += chunk1 + chunk2;
  }
  return result;
}

console.log(reverseStr("12345678", 2));

Reverse string in chunks of size k

//make a variable string with some letters to test.
let str = "abcdefg"; 

//k represents is the number of letters to reverse starting at 0 to position k
let k = 4;  

//select the first k letters and split on blankstring, converting to a list 
//then reversing that list, collapsing it to a string with join, then 
//re-append the original string at position k to the end. 
result = (str.substring(0,k).split('')).reverse().join('') + str.substring(k); 
console.log({result}); 

Prints:

{ result: 'dcbaefg' } 

You can realize it in three steps. First separate the string into k group. Then reverse the string of each group at an even index. Last join all the group together.

   function reverseStr(s, k) {
    return s
      .replace(new RegExp('\\w{' + k + '}', 'g'), $2 => $2 + '|')
      .split('|')
      .map((item, i) =>
        i % 2 !== 0
          ? item
          : item
              .split('')
              .reverse()
              .join('')
      )
      .join('');
  }

  console.log(reverseStr('abcdefg', 2));

Related