I'm currently tackling a coding problem:
For a given string s and an integer k, the task is to reverse the first k characters for every 2k characters starting from the beginning of the string.
If there are less than k characters remaining, reverse all of them. If there are between k and 2k characters left, only reverse the initial k characters and keep the rest unchanged.
I managed to create a program that successfully handles 45 out of the 60 test cases, but it seems to struggle with very lengthy strings. In fact, when provided with strings of 999 characters, the last few outputs were gibberish.
I have thoroughly reviewed my code but cannot pinpoint any errors that might have led to this issue. Any suggestions? Perhaps simpler approaches or more efficient ways to structure my code?
function reverseArrayOfChars(sArray) {
const length = sArray.length;
let temp;
for (let s = 0; s < length / 2; s++) {
temp = sArray[s];
sArray[s] = sArray[length - 1 - s];
sArray[length - 1 - s] = temp;
}
return sArray;
}
function reverseStr(s, k) {
let sArray = s.split("");
let newArray = []; //Final array to be returned
let tempArray = []; //tempArray is used to store returns from reverseArrayOfChars function. These returns are then concatenated onto newArray.
let switchBoard = 1; //Used to 'switch' between two conditions. Changes automatically every iteration of the loop.
for (let counter = 0; counter < sArray.length; counter += k) {
switchBoard = switchBoard === 0 ? 1 : 0;
if (sArray.length - counter < k) {
tempArray = reverseArrayOfChars(sArray.slice(counter));
newArray = newArray.concat(tempArray);
break;
} else if (sArray.length - counter > k && sArray.length < k * 2) {
tempArray = reverseArrayOfChars(sArray.slice(counter, counter + k));
newArray = newArray.concat(tempArray);
tempArray = sArray.slice(counter + k);
newArray = newArray.concat(tempArray);
break;
} else if (switchBoard === 0) {
tempArray = reverseArrayOfChars(sArray.slice(counter, counter + k));
newArray = newArray.concat(tempArray);
} else if (switchBoard === 1) {
tempArray = sArray.slice(counter, counter + k);
newArray = newArray.concat(tempArray);
}
}
return newArray.join("");