Reverse alternate k characters in a string

Given a string str and an integer k, the task is to reverse alternate k characters of the given string. If characters present are less than k, leave them as it is.

Examples:

Input: str = “geeksforgeeks”, k = 3
Output: eegksfgroeeks



Input: str = “abcde”, k = 2
Output: bacde

Approach: The idea is to first reverse k characters, then jump onto the next k characters by adding 2 * k to the index and so on until the complete string is modified.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the string after
// reversing the alternate k characters
string revAlternateK(string s, int k, int len)
{
  
    for (int i = 0; i < s.size();) {
  
        // If there are less than k characters
        // starting from the current position
        if (i + k > len)
            break;
  
        // Reverse first k characters
        reverse(s.begin() + i, s.begin() + i + k);
  
        // Skip the next k characters
        i += 2 * k;
    }
    return s;
}
  
// Driver code
int main()
{
    string s = "geeksforgeeks";
    int len = s.length();
    int k = 3;
    cout << revAlternateK(s, k, len);
  
    return 0;
}

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Function to return the string after
# reversing the alternate k characters
def revAlternateK(s, k, Len):
    i = 0
      
    while(i < len(s)):
  
        # If there are less than k characters
        # starting from the current position
        if (i + k > Len):
            break
  
        # Reverse first k characters
        ss = s[i:i + k]
        s = s[:i]+ss[::-1]+s[i + k:]
          
        # Skip the next k characters
        i += 2 * k
      
    return s;
  
  
# Driver code
  
s = "geeksforgeeks"
Len = len(s)
k = 3
print(revAlternateK(s, k, Len))
  
# This code is contributed by mohit kumar

chevron_right


Output:

eegksfgroeeks


My Personal Notes arrow_drop_up

A Coding Enthusiast Rails Developer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mohit kumar 29



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.