Reverse String II(#541)

Category: String, Two Pointer

๐Ÿงฉ Problem Statement

You're given a 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. Rules: 1. If there are fewer than `k` characters left, reverse all of them. 2. If there are at least `k` but fewer than `2k` characters, then reverse only the first `k`, and leave the rest as-is.

๐Ÿ“š Examples

Input: s = "abcdefg", k = 2

Output: "bacdfeg"

Explanation: First block: "ab" โ†’ "ba", Second block: "ef" โ†’ "fe". Final string: "bacdfeg".

Input: s = "abcd", k = 2

Output: "bacd"

Explanation: Reverse first k = 2 โ†’ "ab" โ†’ "ba", rest stays same โ†’ "bacd".

๐Ÿง  Approach

โ€ข Convert the string into a character array for easy in-place operations.

โ€ข Loop through the string in increments of `2k`.

โ€ข For each chunk, reverse the first `k` characters using two pointers.

โ€ข Use `Math.min(i + k - 1, s.length - 1)` to handle boundary conditions safely.

โ€ข Finally, join the array and return the result.

๐Ÿ’ป Code

var reverseStr = function(s, k) {
    let arr = s.split('');
    for (let i = 0; i < s.length; i += 2 * k) {
        let left = i;
        let right = Math.min(i + k - 1, s.length - 1);
        while (left < right) {
            [arr[left], arr[right]] = [arr[right], arr[left]];
            left++;
            right--;
        }
    }
    return arr.join('');
};

๐Ÿ“ˆ Complexity

Time: O(n) โ€“ We iterate over the string once in chunks.

Space: O(n) โ€“ Due to character array manipulation.

๐ŸŽฌ Watch Explanation

๐Ÿ“Š Presentation (PPT)

๐Ÿ“ฅ Download PPT

๐Ÿ“Ž Resources