Move all occurrence of letter ‘x’ from the string s to the end using Recursion

25 Aug, 2021
Given a string s, our task is to move all the occurrence of letter x to the end of the string s using recursion.Note: If there are only letter x in the given string then return the string unaltered.
Examples: 
Input: s= “geekxsforgexxeksxx” Output: geeksforgeeksxxxxx Explanation: All occurrence of letter ‘x’ is moved to the end.
Input: s = “xxxxx” Output: xxxxx Explanation: Since there are only letter x in the given string therefore the output is unaltered.  
Approach:To solve the problem mentioned above we can use Recursion. Traverse in the string and check recursively if the current character is equal to the character ‘x’ or not. If not then print the character otherwise move to the next character until the length of the string s is reached.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation to Move all occurrence of letter ‘x’// from the string s to the end using Recursion#include <bits/stdc++.h>using namespace std; // Function to move all 'x' in the endvoid moveAtEnd(string s, int i, int l){    if (i >= l)        return;     // Store current character    char curr = s[i];     // Check if current character is not 'x'    if (curr != 'x')        cout << curr;     // recursive function call    moveAtEnd(s, i + 1, l);     // Check if current character is 'x'    if (curr == 'x')        cout << curr;     return;} // Driver codeint main(){    string s = "geekxsforgexxeksxx";     int l = s.length();     moveAtEnd(s, 0, l);     return 0;}
// Java implementation to Move all occurrence of letter ‘x’// from the string s to the end using Recursionimport java.util.*;class GFG{ // Function to move all 'x' in the endstatic void moveAtEnd(String s, int i, int l){    if (i >= l)        return;     // Store current character    char curr = s.charAt(i);     // Check if current character is not 'x'    if (curr != 'x')        System.out.print(curr);     // recursive function call    moveAtEnd(s, i + 1, l);     // Check if current character is 'x'    if (curr == 'x')        System.out.print(curr);     return;} // Driver codepublic static void main(String args[]){    String s = "geekxsforgexxeksxx";     int l = s.length();     moveAtEnd(s, 0, l);}} // This code is contributed by Code_Mech
# Python3 implementation to move all# occurrences of letter ‘x’ from the# string s to the end using recursion # Function to move all 'x' in the enddef moveAtEnd(s, i, l):     if(i >= l):       return     # Store current character    curr = s[i]     # Check if current character    # is not 'x'    if(curr != 'x'):        print(curr, end = "")     # Recursive function call    moveAtEnd(s, i + 1, l)     # Check if current character is 'x'    if(curr == 'x'):        print(curr, end = "")     return # Driver codeif __name__ == '__main__':     s = "geekxsforgexxeksxx"    l = len(s)     moveAtEnd(s, 0, l) # This code is contributed by Shivam Singh
// C# implementation to Move all occurrence of letter ‘x’// from the string s to the end using Recursionusing System;class GFG{ // Function to move all 'x' in the endstatic void moveAtEnd(string s, int i, int l){    if (i >= l)        return;     // Store current character    char curr = s[i];     // Check if current character is not 'x'    if (curr != 'x')        Console.Write(curr);     // recursive function call    moveAtEnd(s, i + 1, l);     // Check if current character is 'x'    if (curr == 'x')        Console.Write(curr);     return;} // Driver codepublic static void Main(){    string s = "geekxsforgexxeksxx";     int l = s.Length;     moveAtEnd(s, 0, l);}} // This code is contributed by Nidhi_Biet
<script> // Javascript implementation to Move// all occurrence of letter ‘x’ from// the string s to the end using Recursion // Function to move all 'x' in the endfunction moveAtEnd(s, i, l){    if (i >= l)        return;     // Store current character    let curr = s[i];     // Check if current character is not 'x'    if (curr != 'x')        document.write(curr);     // Recursive function call    moveAtEnd(s, i + 1, l);     // Check if current character is 'x'    if (curr == 'x')        document.write(curr);     return;} // Driver codelet s = "geekxsforgexxeksxx";let l = s.length; moveAtEnd(s, 0, l); // This code is contributed by suresh07 </script>
  
geeksforgeeksxxxxx
 
Another Implementation involving swapping of characters:
 
In this approach, we will be swapping adjacent characters to bring ‘x’ at the end.
 
Below is the implementation of the above technique:
 
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include<bits/stdc++.h>using namespace std; // Recursive program to bring 'x'// to the endvoid rec(char *a, int i){         // When the string is completed    // from reverse direction end of recursion    if(i == 0)    {      cout << a << endl;      return;    }       // If the character x is found    if(a[i] == 'x')    {             // Transverse the whole string      int j = i;      while(a[j] != '\0' && a[j+1] != '\0')      {                 // Swap the x so that        // it moves to the last        swap(a[j], a[j+1]);        j++;      }    }       // call to the smaller problem now    rec(a, i - 1);} // Driver Codeint main(){    char a[] = {'g', 'e', 'e', 'k', 'x',            's', 'x', 'x', 'k', 's', '\0'};         // Size of a    int n = 10;       // Call to rec    rec(a,n-1);}/* This code is contributed by Harsh kedia */
// Java program for the// above approachimport java.util.*;class Main{     // Recursive program to// bring 'x' to the endpublic static void rec(char a[],                       int i){          // When the string is completed  // from reverse direction end  // of recursion  if(i == 0)  {    System.out.println(a);    return;  }   // If the character x is found  if(a[i] == 'x')  {     // Transverse the whole string    int j = i;    while(a[j] != '\0' &&          a[j + 1] != '\0')    {      // Swap the x so that      // it moves to the last      char temp = a[j];      a[j] = a[j + 1];      a[j + 1] = temp;      j++;    }  }   // call to the smaller  // problem now  rec(a, i - 1);}   // Driver codepublic static void main(String[] args){  char a[] = {'g', 'e', 'e', 'k',              'x', 's', 'x', 'x',              'k', 's', '\0'};   // Size of a  int n = 10;   // Call to rec  rec(a,n-1);}} // This code is contributed by divyeshrabadiya07
# Python3 program for above approach # Recursive program to bring 'x'# to the enddef rec(a, i):          # When the string is completed    # from reverse direction end    # of recursion    if (i == 0):        a.pop()        print("".join(a))        return         # If the character x is found    if (a[i] == 'x'):              # Transverse the whole string      j = i      while(a[j] != '\0' and            a[j + 1] != '\0'):                  # Swap the x so that        # it moves to the last        (a[j], a[j + 1]) = (a[j + 1], a[j])        j += 1           # Call to the smaller problem now    rec(a, i - 1) # Driver codeif __name__=="__main__":         a = [ 'g', 'e', 'e', 'k', 'x',          's', 'x', 'x', 'k', 's', '\0' ]          # Size of a    n = 10        # Call to rec    rec(a, n - 1) # This code is contributed by rutvik_56
// C# program for the// above approachusing System;class GFG{         // Recursive program to    // bring 'x' to the end    static void rec(char[] a, int i)    {             // When the string is completed      // from reverse direction end      // of recursion      if(i == 0)      {        Console.WriteLine(a);        return;      }            // If the character x is found      if(a[i] == 'x')      {              // Transverse the whole string        int j = i;        while(a[j] != '\0' &&              a[j + 1] != '\0')        {                     // Swap the x so that          // it moves to the last          char temp = a[j];          a[j] = a[j + 1];          a[j + 1] = temp;          j++;        }      }            // call to the smaller      // problem now      rec(a, i - 1);    }     // Driver code      static void Main()  {      char[] a = {'g', 'e', 'e', 'k',              'x', 's', 'x', 'x',              'k', 's', '\0'};        // Size of a      int n = 10;            // Call to rec      rec(a,n-1);  }} // This code is contributed by divyesh072019
<script>    // Javascript program for the above approach         // Recursive program to    // bring 'x' to the end    function rec(a, i)    {              // When the string is completed      // from reverse direction end      // of recursion      if(i == 0)      {        document.write(a.join(""));        return;      }             // If the character x is found      if(a[i] == 'x')      {               // Transverse the whole string        let j = i;        while(a[j] != '\0' &&              a[j + 1] != '\0')        {                      // Swap the x so that          // it moves to the last          let temp = a[j];          a[j] = a[j + 1];          a[j + 1] = temp;          j++;        }      }             // call to the smaller      // problem now      rec(a, i - 1);    }         let a = ['g', 'e', 'e', 'k', 'x', 's', 'x', 'x', 'k', 's', '\0'];       // Size of a    let n = 10;     // Call to rec    rec(a, n - 1);         // This code is contributed by decode2207.</script>
  
geeksksxxx
Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(N). 
SHIVAMSINGH67
nidhi_biet
Code_Mech
harsh2608
rutvik_56
divyeshrabadiya07
divyesh072019
suresh07
decode2207
clintra
pankajsharmagfg
khushboogoyal499
Google
Algorithms
Recursion
Strings
Write From Home
Google
Strings
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
Understanding Time Complexity with Simple Examples
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Tower of Hanoi
Backtracking | Introduction
Print all subsequences of a string