Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created November 10, 2024 07:54
Show Gist options
  • Save sAVItar02/ee0121feff58f61900a4e612a7de8391 to your computer and use it in GitHub Desktop.
Save sAVItar02/ee0121feff58f61900a4e612a7de8391 to your computer and use it in GitHub Desktop.
Reverse String 2
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var reverseStr = function(s, k) {
let reverseFrom = (i, j) => {
s = s.split("");
while(i<j) {
let temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
s = s.join("");
}
let i = 0;
let shouldReverse = 1;
if(s.length <= k) {
s = s.split("");
s.reverse();
s = s.join("");
return s;
}
while(i < s.length - k) {
reverseFrom(i, i+k - 1);
console.log(s);
i = i + 2*k;
if(s.length - i <= k) {
reverseFrom(i, s.length - 1);
}
}
return s;
};
// Function: reverseFrom: Takes 2 arguments, from position and to position, then it reverses that part of the string
// run a loop on the string and reverse from i to i+k, then move the i value 2k times ahead to skip the next k characters
// if i is less than 2k then reverse first k
// if i is less than k then reverse all
// Time: O(n)
// Space: O(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment