Problem statement

https://leetcode.com/problems/reverse-string-ii/

Solution

Just do what is asked, go with step 2k and reverse groups of k elements. Note, that in python if we have a = "0123456789", then a[7:15] = "789", so we do not need to worry about the last reverse.

Complexity

Time and space complexity is O(n).

Code

class Solution:
    def reverseStr(self, s, k):
        s_list = list(s)
        for i in range(0, len(s), 2*k):
            s_list[i:i+k] = s_list[i:i+k][::-1]
        return "".join(s_list)