

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Example
Let us see the following implementation to get a better understanding −
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))
Input
"abcdefg", 3
Output
cbadefg
- Related Questions & Answers
- Reverse Words in a String II in C++
- Reverse Linked List II in C++
- Reverse String in Python
- How to reverse a string in Python?
- Reverse Vowels of a String in Python
- String reverse vs reverse! function in Ruby
- 4Sum II in Python
- Reverse words in a given String in Python
- How to reverse a string in Python program?
- Spiral Matrix II in Python
- Single Number II in Python
- Basic Calculator II in Python
- Course Schedule II in Python
- Jump Game II in Python
- Word Break II in Python