KatInterview

541. Reverse String II

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to reverse specific segments of a given string s based on an integer k. The rule is to consider the string in chunks of 2k characters. In each chunk, we must reverse the first k characters. The problem also specifies how to handle the end of the string if it doesn't align perfectly with 2k chunks:

Solution

Reverse String II in Python

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        # Convert string to a list of characters as strings are immutable in Python.
        a = list(s)
        n = len(a)
        
        # Iterate through the list with a step of 2k.
        for i in range(0, n, 2 * k):
            # The slice to reverse is a[i:i+k].
            # Python's slicing handles the boundary case where i+k > n automatically.
            # For example, if n=7, k=2, i=4, a[4:6] is correct.
            # If n=7, k=4, i=4, a[4:8] becomes a[4:7], which is also correct.
            # We reverse this slice and assign it back.
            segment = a[i:i+k]
            segment.reverse() # In-place reverse of the slice
            a[i:i+k] = segment
            
            # A more Pythonic one-liner for the reversal:
            # a[i:i+k] = reversed(a[i:i+k])
            # or
            # a[i:i+k] = a[i:i+k][::-1]

        # Join the list of characters back into a string.
        return "".join(a)

Reverse String II in Java

class Solution {
    public String reverseStr(String s, int k) {
        char[] a = s.toCharArray();
        int n = a.length;
        
        // Iterate through the string with a step of 2k.
        for (int i = 0; i < n; i += 2 * k) {
            // The start of the segment to reverse.
            int start = i;
            // The end of the segment to reverse (inclusive).
            // It's the minimum of i + k - 1 and the last index of the string.
            // This handles all cases correctly.
            int end = Math.min(i + k - 1, n - 1);
            
            // Reverse the sub-array in place.
            reverse(a, start, end);
        }
        
        return new String(a);
    }

    // Helper function to reverse a part of a char array.
    private void reverse(char[] a, int i, int j) {
        while (i < j) {
            char temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
    }
}

Reverse String II in C++

class Solution {
public:
    string reverseStr(string s, int k) {
        int n = s.length();
        // Iterate through the string with a step of 2k.
        for (int i = 0; i < n; i += 2 * k) {
            // The start of the segment to reverse is i.
            int start = i;
            // The end of the segment to reverse (exclusive for std::reverse).
            // It's the minimum of i + k and the total length of the string.
            // This handles all cases: remaining chars < k, k <= remaining chars < 2k.
            int end = min(i + k, n);
            
            // Reverse the substring from s.begin() + start to s.begin() + end.
            reverse(s.begin() + start, s.begin() + end);
        }
        return s;
    }
};

Reverse String II in TypeScript

function reverseStr(s: string, k: number): string {
    // Convert string to an array of characters as strings are immutable.
    const a = s.split('');
    const n = a.length;

    // Iterate through the array with a step of 2k.
    for (let i = 0; i < n; i += 2 * k) {
        // The start of the segment to reverse.
        let start = i;
        // The end of the segment to reverse (inclusive).
        // Math.min handles cases where fewer than k characters are left.
        let end = Math.min(i + k - 1, n - 1);

        // Reverse the sub-array in place using a two-pointer swap.
        while (start < end) {
            const temp = a[start];
            a[start] = a[end];
            a[end] = temp;
            start++;
            end--;
        }
    }

    // Join the array of characters back into a string.
    return a.join('');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.