Reverse String II in Python

Suppose we have a string and an integer k, we have to reverse the first k characters for every 2k characters counting from the start of the string. If there is no sufficient character left, then reverse all of them. If there are less than 2k characters but greater than or equal to k characters, then reverse the first k characters and left the other as original.

So, if the input is like "abcdefgh" and k = 3, then the output will be "cbadefhg"

To solve this, we will follow these steps −

  • l := make a list of characters of s

  • i := k-1

  • while i < size of l + k −

    • a := l[from index 0 to i-k+1]

    • b := l[from index i-k+1 to i+1]

    • c := l[from index i+1 to end]

    • l := a concatenate b[from index 0 to end] concatenate c

    • i := i + 2*k

  • return string by concatenating each character in l


Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def reverseStr(self, s, k):
      l = list(s)
      i = k-1
      while i < len(l)+k:
         a = l[:i-k+1]
         b = l[i-k+1:i+1]
         c = l[i+1:]
         l = a + b[::-1] + c
         i += 2*k
      return ''.join(l)

ob = Solution()
print(ob.reverseStr("abcdefg", 3))


"abcdefg", 3