Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse string in alternating chunks of size k

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?

like image 944
user944513 Avatar asked Nov 26 '25 05:11

user944513


2 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))
like image 180
CertainPerformance Avatar answered Nov 27 '25 19:11

CertainPerformance


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));
like image 42
Barmar Avatar answered Nov 27 '25 18:11

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!