Program to reverse a string (Iterative and Recursive) - GeeksforGeeks (2023)

kartikmaster118 published articles
  • Read
  • Discuss

    Improve Article

    Improve

    Save Article

    Save

    Like Article

    Like

    Given a string, write a recursive program to reverse it

    Program to reverse a string (Iterative and Recursive) - GeeksforGeeks (2)

    String Reverse

    Reverse String using Stack:

    The idea is to push all the characters of the string in a stack. Then pop the elements of the stack and store it in the initial string from the starting index. Since the stack is based on last in first out, so the string formed will be reverse of the original string.

    Below is the implementation of the above approach:

    C++

    // C++ program to reverse a string using stack

    #include <bits/stdc++.h>

    using namespace std;

    void reversebyStack(string &str)

    {

    // To store the characters of original string.

    stack<char> st;

    for (int i=0; i<str.length(); i++)

    // Push the charcters into stack

    st.push(str[i]);

    for (int i=0; i<str.length(); i++) {

    // Pop the charcters of stack into the original string.

    str[i] = st.top();

    st.pop();

    }

    }

    // Driver program

    int main()

    {

    // Original String

    string str = "geeksforgeeks";

    reversebyStack(str);

    cout << str;

    return 0;

    }

    Java

    // Java program to reverse a string using stack

    import java.util.*;

    class GFG

    {

    public static String reversebyStack(char []str)

    {

    Stack<Character> st = new Stack<>();

    for(int i=0; i<str.length; i++)

    // Push the charcters into stack

    st.push(str[i]);

    for (int i=0; i<str.length; i++) {

    // Pop the charcters of stack into the original string.

    str[i] = st.peek();

    st.pop();

    }

    return String.valueOf(str);// converting character array to string

    }

    // Driver program

    public static void main(String []args)

    {

    String str = "geeksforgeeks";

    str = reversebyStack(str.toCharArray());// passing character array as parameter

    System.out.println(str);

    }

    }

    // This code is contributed by Adarsh_Verma

    Python3

    # Python program to reverse a string using stack

    def reversebyStack(str):

    # using as stack

    stack = []

    for i in range(len(str)):

    # Push the charcters into stack

    stack.append(str[i])

    for i in range(len(str)):

    # Pop the charcters of stack into the original string.

    str[i] = stack.pop()

    if __name__ == "__main__":

    str = "geeksforgeeks"

    # converting string to list

    # because strings do not support

    # item assignment

    str = list(str)

    reversebyStack(str)

    # converting list to string

    str = ''.join(str)

    print(str)

    # This code is contributed by

    # sanjeev2552

    C#

    // C# program to reverse a string using stack

    using System;

    using System.Collections.Generic;

    class GFG

    {

    public static String reversebyStack(char []str)

    {

    Stack<char> st = new Stack<char>();

    for(int i = 0; i < str.Length; i++)

    // Push the charcters into stack

    st.Push(str[i]);

    for (int i = 0; i < str.Length; i++)

    {

    // Pop the charcters of stack into the original string.

    str[i] = st.Peek();

    st.Pop();

    }

    // converting character array to string

    return String.Join("",str);

    }

    // Driver program

    public static void Main()

    {

    String str = "geeksforgeeks";

    // passing character array as parameter

    str = reversebyStack(str.ToCharArray());

    Console.WriteLine(str);

    }

    }

    // This code is contributed by Rajput-Ji

    Javascript

    // Function to reverse a string using a stack

    function reverseByStack(str) {

    // To store the characters of the original string.

    const stack = [];

    // Push the characters into the stack.

    for (let i = 0; i < str.length; i++) {

    stack.push(str[i]);

    }

    // Pop the characters of the stack and build the reversed string.

    let reversedStr = '';

    while (stack.length > 0) {

    reversedStr += stack.pop();

    }

    return reversedStr;

    }

    // Driver program

    function main() {

    // Original String

    let str = "geeksforgeeks";

    let reversedStr = reverseByStack(str);

    console.log(reversedStr);

    }

    main();

    // This code is contributed by shivamgupta0987654321

    Output

    skeegrofskeeg

    Time Complexity: O(n)
    Auxiliary Space: O(n)

    Reverse String using two pointers:

    The idea is to use two pointers. The left pointer is placed at the beginning of the string and the right pointer is placed at the end of the string. Now swap the characters at left and right pointers, after that left pointer moves forward by 1 step and right pointer moves backward by 1 step. This operation is continued till right pointer is ahead of left pointer.

    Below is the implementation of the above approach:

    C++

    // A Simple Iterative C++ program to reverse

    // a string

    #include <bits/stdc++.h>

    using namespace std;

    // Function to reverse a string

    void reverseStr(string& str)

    {

    int n = str.length();

    // Swap character starting from two

    // corners

    // i is the left pointer and j is the right pointer

    for (int i = 0, j = n - 1; i < j; i++, j--)

    swap(str[i], str[j]);

    }

    // Driver program

    int main()

    {

    string str = "geeksforgeeks";

    reverseStr(str);

    cout << str;

    return 0;

    }

    Java

    //A Simple Iterative Java program to reverse

    //a string

    import java.io.*;

    class GFG {

    //Function to reverse a string

    static void reverseStr(String str)

    {

    int n = str.length();

    char []ch = str.toCharArray();

    char temp;

    // Swap character starting from two

    // corners

    // i is the left pointer and j is the right pointer

    for (int i=0, j=n-1; i<j; i++,j--)

    {

    temp = ch[i];

    ch[i] = ch[j];

    ch[j] = temp;

    }

    System.out.println(ch);

    }

    //Driver program

    public static void main(String[] args) {

    String str = "geeksforgeeks";

    reverseStr(str);

    }

    }

    // This code is contributed by Ita_c.

    Python3

    # A Simple Iterative Python program to

    # reverse a string

    # Function to reverse a string

    def reverseStr(str):

    n = len(str)

    i, j = 0, n-1

    # Swap character starting from

    # two corners

    # i is the left pointer and j is the right pointer

    while i < j:

    str[i], str[j] = str[j], str[i]

    i += 1

    j -= 1

    # Driver code

    if __name__ == "__main__":

    str = "geeksforgeeks"

    # converting string to list

    # because strings do not support

    # item assignment

    str = list(str)

    reverseStr(str)

    # converting list to string

    str = ''.join(str)

    print(str)

    # This code is contributed by

    # sanjeev2552

    C#

    // A Simple Iterative C# program

    // to reverse a string

    using System;

    class GFG

    {

    //Function to reverse a string

    static void reverseStr(String str)

    {

    int n = str.Length;

    char []ch = str.ToCharArray();

    char temp;

    // Swap character starting from two

    // corners

    // i is the left pointer and j is the right pointer

    for (int i=0, j=n-1; i<j; i++,j--)

    {

    temp = ch[i];

    ch[i] = ch[j];

    ch[j] = temp;

    }

    Console.WriteLine(ch);

    }

    //Driver program

    public static void Main(String[] args)

    {

    String str = "geeksforgeeks";

    reverseStr(str);

    }

    }

    // This code is contributed by PrinciRaj1992

    Javascript

    <script>

    //A Simple Iterative Javascript program to reverse

    //a string

    //Function to reverse a string

    function reverseStr(str)

    {

    let n = str.length;

    let ch = str.split("");

    let temp;

    // Swap character starting from two

    // corners

    // i is the left pointer and j is the right pointer

    for (let i=0, j=n-1; i<j; i++,j--)

    {

    temp = ch[i];

    ch[i] = ch[j];

    ch[j] = temp;

    }

    document.write(ch.join("")+"<br>");

    }

    //Driver program

    let str = "geeksforgeeks";

    reverseStr(str);

    // This code is contributed by rag2127

    </script>

    PHP

    <?php

    // A Simple Iterative PHP

    // program to reverse a string

    // Function to reverse a string

    function reverseStr (&$str)

    {

    $n = strlen($str);

    // Swap character starting

    // from two corners

    for ($i = 0, $j = $n - 1;

    $i < $j; $i++, $j--)

    //swap function

    list($str[$i],

    $str[$j]) = array($str[$j],

    $str[$i]);

    }

    // Driver Code

    $str = "geeksforgeeks";

    reverseStr($str);

    echo $str;

    // This code is contributed by ajit.

    ?>

    Output

    skeegrofskeeg

    Time Complexity: O(n)
    Auxiliary Space: O(1)

    Reverse String using Recursion:

    The recursive algorithm to reverse a string works by swapping the first and last characters until the middle of the string is reached. This process is performed through recursive calls, where in each call, characters at positions i and n-i-1 are swapped, and i is incremented. This continues until i reaches n/2, and the string is completely reversed.

    Below is the implementation of the above approach:

    C++

    // Recursive C++ program to reverse a string

    #include <bits/stdc++.h>

    using namespace std;

    // Recursive function to reverse the string

    void recursiveReverse(string &str, int i = 0)

    {

    int n = str.length();

    if (i == n / 2)

    return;

    // Swap the i and n-i-1 character

    swap(str[i], str[n - i - 1]);

    // Call Recursive function after incrementing i.

    recursiveReverse(str, i + 1);

    }

    // Driver program

    int main()

    {

    string str = "geeksforgeeks";

    recursiveReverse(str);

    cout << str;

    return 0;

    }

    Java

    // Recursive Java program to reverse a string

    import java.io.*;

    class GFG

    {

    // Recursive function to reverse the string

    static void recursiveReverse(char[] str, int i)

    {

    int n = str.length;

    if (i == n / 2)

    return;

    // Swap the i and n-i-1 character

    swap(str,i,n - i - 1);

    // Call Recursive function after incrementing i.

    recursiveReverse(str, i + 1);

    }

    static void swap(char []arr, int i, int j)

    {

    char temp= arr[i];

    arr[i]=arr[j];

    arr[j]=temp;

    }

    // Driver program

    public static void main(String[] args)

    {

    char[] str = "geeksforgeeks".toCharArray();

    recursiveReverse(str,0);

    System.out.println(String.valueOf(str));

    }

    }

    // This code is contributed by 29AjayKumar

    Python3

    # Recursive Python program to reverse a string

    def recursiveReverse(str, i = 0):

    n = len(str)

    if i == n // 2:

    return

    # Swap the i and n-i-1 character

    str[i], str[n-i-1] = str[n-i-1], str[i]

    # Call Recursive function after incrementing i.

    recursiveReverse(str, i+1)

    if __name__ == "__main__":

    str = "geeksforgeeks"

    # converting string to list

    # because strings do not support

    # item assignment

    str = list(str)

    recursiveReverse(str)

    # converting list to string

    str = ''.join(str)

    print(str)

    # This code is contributed by

    # sanjeev2552

    C#

    // Recursive C# program to reverse a string

    using System;

    public class GFG

    {

    static void recursiveReverse(char[] str, int i)

    {

    int n = str.Length;

    if (i == n / 2)

    return;

    // Swap the i and n-i-1 character

    swap(str,i,n - i - 1);

    // Call Recursive function after incrementing i.

    recursiveReverse(str, i + 1);

    }

    static char[] swap(char []arr, int i, int j)

    {

    char temp= arr[i];

    arr[i]=arr[j];

    arr[j]=temp;

    return arr;

    }

    // Driver program

    public static void Main(String[] args)

    {

    char[] str = "geeksforgeeks".ToCharArray();

    recursiveReverse(str,0);

    Console.WriteLine(String.Join("",str));

    }

    }

    // This code is contributed by Princi Singh

    Javascript

    // Recursive JavaScript function to reverse a string

    function recursiveReverse(str, i = 0) {

    const n = str.length;

    if (i >= Math.floor(n / 2))

    return str;

    // Swap the i and n-i-1 characters

    str = str.substring(0, i) + str[n - i - 1] + str.substring(i + 1, n - i - 1) + str[i] + str.substring(n - i);

    // Call Recursive function after incrementing i.

    return recursiveReverse(str, i + 1);

    }

    // Driver program

    let str = "geeksforgeeks";

    str = recursiveReverse(str);

    console.log(str);

    PHP

    <?php

    // A Simple PHP program

    // to reverse a string

    // Function to reverse a string

    function reverseStr($str)

    {

    // print the string

    // from last

    echo strrev($str);

    }

    // Driver Code

    $str = "geeksforgeeks";

    reverseStr($str);

    // This code is contributed

    // by Srathore

    ?>

    Output

    skeegrofskeeg

    Time Complexity: O(n) where n is length of string
    Auxiliary Space: O(n)

    Reverse String using inbuilt method

    Below is the implementation to reverse a string using built-in methods in different programming languages:

    C++

    #include <bits/stdc++.h>

    using namespace std;

    int main()

    {

    string str = "geeksforgeeks"; // Input string

    reverse(str.begin(),str.end()); // Reverse the string

    cout << str << std::endl;

    return 0;

    }

    // This code is contributed by prajwalkandekar123.

    Java

    //Java program to reverse a string using StringBuffer class

    import java.io.*;

    import java.util.*;

    class GFG {

    //Driver Code

    public static void main (String[] args) {

    String str = "geeksforgeeks";//Input String

    //Step 1: Initialise an object of StringBuffer class

    StringBuffer sb = new StringBuffer(str);

    //Step 2: Invoke the .reverse() method

    sb.reverse();

    //Step 3: Convert the StringBuffer to string by using toString() method

    System.out.println(sb.toString());

    }

    }

    //This code is contributed by shruti456rawal

    Python3

    # Driver Code

    if __name__ == '__main__':

    str = "geeksforgeeks" # Input String

    # Step 1: Initialise an object of StringBuffer class

    sb = str[::-1]

    # Step 2: Invoke the .reverse() method (not applicable in Python)

    # Step 3: Print the reversed string

    print(sb)

    C#

    // c# code

    using System;

    class Program {

    static void Main(string[] args)

    {

    string str = "geeksforgeeks"; // Input string

    char[] charArray

    = str.ToCharArray(); // Convert string to char

    // array

    Array.Reverse(charArray); // Reverse the array

    str = new string(

    charArray); // Convert char array back to string

    Console.WriteLine(

    str); // Output the reversed string

    }

    }

    // ksam24000

    Javascript

    let str = "geeksforgeeks"; // Input string

    str = str.split('').reverse().join(''); // Reverse the string

    console.log(str);

    // This code is contributed by Prajwal Kandekar

    Output

    skeegrofskeeg

    Time Complexity: O(n)
    Auxiliary Space: O(1) in all the programming languages except Java in which it will be, O(n) (The extra space is used to store the StringBuffer string).


    Last Updated :22 Aug, 2023

    Like Article

    Save Article

    Top Articles
    Latest Posts
    Article information

    Author: Jonah Leffler

    Last Updated: 27/01/2024

    Views: 6009

    Rating: 4.4 / 5 (65 voted)

    Reviews: 88% of readers found this page helpful

    Author information

    Name: Jonah Leffler

    Birthday: 1997-10-27

    Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

    Phone: +2611128251586

    Job: Mining Supervisor

    Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

    Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.