Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Left Rotation of a String
Next article icon

Reverse a String – Complete Tutorial

Last Updated : 04 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a string s, the task is to reverse the string. Reversing a string means rearranging the characters such that the first character becomes the last, the second character becomes second last and so on.

Examples:

Input: s = "GeeksforGeeks"
Output: "skeeGrofskeeG"
Explanation : The first character G moves to last position, the second character e moves to second-last and so on.

Input: s = "abdcfe"
Output: "efcdba"
Explanation: The first character a moves to last position, the second character b moves to second-last and so on.

Table of Content

  • Using backward traversal – O(n) Time and O(n) Space
  • Using Two Pointers - O(n) Time and O(1) Space
  • Using Recursion - O(n) Time and O(n) Space
  • Using Stack - O(n) Time and O(n) Space
  • Using Inbuilt methods - O(n) Time and O(1) Space

Using backward traversal – O(n) Time and O(n) Space

The idea is to start at the last character of the string and move backward, appending each character to a new string res. This new string res will contain the characters of the original string in reverse order.

C++
// C++ program to reverse a string using backward traversal

#include <iostream>
#include <string>
using namespace std;

string reverseString(string& s) {
    string res;
  
  	// Traverse on s in backward direction
  	// and add each charecter to a new string
    for (int i = s.size() - 1; i >= 0; i--) {
        res += s[i];
    }
    return res;
}

int main() {
    string s = "abdcfe";
    string res = reverseString(s);
    cout << res;
    return 0;
}
C
// C program to reverse a string using backward traversal

#include <stdio.h>
#include <string.h>

char *reverseString(char *s) {
    int n = strlen(s);
    char *res = (char *)malloc((n + 1) * sizeof(char));

    int j = 0;
    
    // Traverse on s in backward direction
    // and add each character to a new string
    for (int i = n - 1; i >= 0; i--) {
        res[j] = s[i];
        j++;
    }

    // Null-terminate the result string
    res[n] = '\0';
    return res;
}

int main() {
    char s[] = "abdcfe";
    char *res = reverseString(s);
    printf("%s", res);
    return 0;
}
Java
// Java program to reverse a string using backward traversal

class GfG {
    static String reverseString(String s) {
        StringBuilder res = new StringBuilder();
  
        // Traverse on s in backward direction
        // and add each character to a new string
        for (int i = s.length() - 1; i >= 0; i--) {
            res.append(s.charAt(i));
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String s = "abdcfe";
        String res = reverseString(s);
        System.out.print(res);
    }
}
Python
# Python program to reverse a string using backward traversal

def reverseString(s):
    res = []
  
    # Traverse on s in backward direction
    # and add each character to the list
    for i in range(len(s) - 1, -1, -1):
        res.append(s[i])

    # Convert list back to string
    return ''.join(res)

if __name__ == "__main__":
    s = "abdcfe"
    print(reverseString(s))
C#
// C# program to reverse a string using backward traversal

using System;
using System.Text;

class GfG {
    static string reverseString(string s) {
        StringBuilder res = new StringBuilder();
  
        // Traverse on s in backward direction
        // and add each character to a new string
        for (int i = s.Length - 1; i >= 0; i--) {
            res.Append(s[i]);
        }
      
        // Convert StringBuilder to string
        return res.ToString(); 
    }

    static void Main(string[] args) {
        string s = "abdcfe";
        string res = reverseString(s);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to reverse a string using backward traversal

function reverseString(s) {
    let res = [];
  
    // Traverse on s in backward direction
    // and add each character to the array
    for (let i = s.length - 1; i >= 0; i--) {
        res.push(s[i]);
    }
    return res.join('');
}

const s = "abdcfe";
console.log(reverseString(s));

Output
efcdba

Time Complexity: O(n) for backward traversal
Auxiliary Space: O(n) for storing the reversed string.

Using Two Pointers - O(n) Time and O(1) Space

The idea is to maintain two pointers: left and right, such that left points to the beginning of the string and right points to the end of the string.

While left pointer is less than the right pointer, swap the characters at these two positions. After each swap, increment the left pointer and decrement the right pointer to move towards the center of the string. This will swap all the characters in the first half with their corresponding character in the second half.

Illustration:



C++
// C++ program to reverse a string using two pointers

#include <bits/stdc++.h>
using namespace std;

string reverseString(string &s) {
    int left = 0, right = s.length() - 1;

    // Swap characters from both ends till we reach
    // the middle of the string
    while (left < right) {
        swap(s[left], s[right]);
        left++;
        right--;
    }
  
    return s;
}

int main() {
    string s = "abdcfe";
    cout << reverseString(s);
    return 0;
}
C
// C program to reverse a string using two pointers

#include <stdio.h>
#include <string.h>

char* reverseString(char *s) {
    int left = 0, right = strlen(s) - 1;

    // Swap characters from both ends till we reach
    // the middle of the string
    while (left < right) {
        char temp = s[left];
        s[left] = s[right];
        s[right] = temp;
        left++;
        right--;
    }
  
    return s;
}

int main() {
    char s[] = "abdcfe"; 
    printf("%s", reverseString(s)); 
    return 0;
}
Java
// Java program to reverse a string using two pointers

class GfG {
    static String reverseString(String s) {
        int left = 0, right = s.length() - 1;
      
        // Use StringBuilder for mutability
        StringBuilder res = new StringBuilder(s);
      
        // Swap characters from both ends till we reach
        // the middle of the string
        while (left < right) {
            char temp = res.charAt(left);
            res.setCharAt(left, res.charAt(right));
            res.setCharAt(right, temp);
            left++;
            right--;
        }
  
        // Convert StringBuilder back to string
        return res.toString();
    }

    public static void main(String[] args) {
        String s = "abdcfe";
        System.out.println(reverseString(s));
    }
}
Python
# Python program to reverse a string using two pointers

# Function to reverse a string using two pointers

def reverseString(s):
    left = 0
    right = len(s) - 1
    
    # Convert string to a list for mutability
    s = list(s)  
    
    # Swap characters from both ends till we reach
    # the middle of the string
    while left < right:
        s[left], s[right] = s[right], s[left]
        left += 1
        right -= 1
    
    # Convert list back to string
    return ''.join(s)  

if __name__ == "__main__":
    s = "abdcfe"
    print(reverseString(s))
C#
// C# program to reverse a string using two pointers

using System;
using System.Text;

class GfG {
    static string reverseString(string s) {
      
        // Use StringBuilder for mutability
        StringBuilder res = new StringBuilder(s); 
        int left = 0, right = res.Length - 1;

        // Swap characters from both ends till we reach
        // the middle of the string
        while (left < right) {
            char temp = res[left];
            res[left] = res[right];
            res[right] = temp;
            left++;
            right--;
        }
  
        // Convert StringBuilder back to string
        return res.ToString(); 
    }

    static void Main(string[] args) {
        string s = "abdcfe";
        Console.WriteLine(reverseString(s));
    }
}
JavaScript
// JavaScript program to reverse a string using two pointers

function reverseString(s) {
    let left = 0, right = s.length - 1;

    // Convert string to array for mutability
    s = s.split(''); 
    
    // Swap characters from both ends till we reach
    // the middle of the string
    while (left < right) {
        [s[left], s[right]] = [s[right], s[left]];
        left++;
        right--;
    }
  
    return s.join('');
}

const s = "abdcfe";
console.log(reverseString(s));

Output
efcdba

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

Using Recursion - O(n) Time and O(n) Space

The idea is to use recursion and define a recursive function that takes a string as input and reverses it. Inside the recursive function,

  • Swap the first and last element.
  • Recursively call the function with the remaining substring.
C++
// C++ Program to reverse an array using Recursion

#include <iostream>
#include <vector>
using namespace std;

// recursive function to reverse a string from l to r
void reverseStringRec(string &s, int l, int r) {
  
    // If the substring is empty, return
    if(l >= r)
        return;
  
    swap(s[l], s[r]);
  	
    // Recur for the remaining string
    reverseStringRec(s, l + 1, r - 1);
}

// function to reverse a string
string reverseString(string &s) {
    int n = s.length();
    reverseStringRec(s, 0, n - 1);
  	return s;
}

int main() {
    string s = "abdcfe";
  	cout << reverseString(s) << endl;
    return 0;
}
C
// C program to reverse a string using Recursion

#include <stdio.h>
#include <string.h>

// Recursive function to reverse a string from l to r
void reverseStringRec(char *s, int l, int r) {
    if (l >= r)
        return;

    // Swap the characters at the ends
    char temp = s[l];
    s[l] = s[r];
    s[r] = temp;

    // Recur for the remaining string
    reverseStringRec(s, l + 1, r - 1);
}

char* reverseString(char *s) {
    int n = strlen(s);
    reverseStringRec(s, 0, n - 1);
  	return s;
}

int main() {
    char s[] = "abdcfe";
  
    printf("%s\n", reverseString(s));
    return 0;
}
Java
// Java program to reverse a string using Recursion

class GfG {
  
    // Recursive function to reverse a string from l to r
    static void reverseStringRec(char[] s, int l, int r) {
        if (l >= r)
            return;

        // Swap the characters at the ends
        char temp = s[l];
        s[l] = s[r];
        s[r] = temp;

        // Recur for the remaining string
        reverseStringRec(s, l + 1, r - 1);
    }

    // Function to reverse a string
    static String reverseString(String s) {
        char[] arr = s.toCharArray();
        reverseStringRec(arr, 0, arr.length - 1);
        return new String(arr);
    }
	
    public static void main(String[] args) {
        String s = "abdcfe";
        System.out.println(reverseString(s));
    }
}
Python
# Python program to reverse a string using Recursion

# Recursive Function to reverse a string
def reverseStringRec(arr, l, r):
    if l >= r:
        return

    # Swap the characters at the ends
    arr[l], arr[r] = arr[r], arr[l]

    # Recur for the remaining string
    reverseStringRec(arr, l + 1, r - 1)

def reverseString(s):
  
  	# Convert string to list of characters
    arr = list(s)  
    reverseStringRec(arr, 0, len(arr) - 1)
    
    # Convert list back to string
    return ''.join(arr)  

if __name__ == "__main__":
    s = "abdcfe"
    print(reverseString(s))
C#
// C# program to reverse a string using Recursion

using System;
using System.Text;

class GfG {
  
    // recursive function to reverse a string from l to r
    static void reverseStringRec(StringBuilder s, int l, int r) {
        if (l >= r)
            return;

        char temp = s[l];
        s[l] = s[r];
        s[r] = temp;

        // Recur for the remaining string
        reverseStringRec(s, l + 1, r - 1);
    }

    // function to reverse a string
    static string reverseString(string input) {
        StringBuilder s = new StringBuilder(input);
        int n = s.Length;
        reverseStringRec(s, 0, n - 1);
        return s.ToString();
    }

    static void Main() {
        string s = "abdcfe";
        Console.WriteLine(reverseString(s));
    }
}
JavaScript
// JavaScript program to reverse a string using Recursion

// Recursive Function to reverse a string
function reverseStringRec(res, l, r) {
    if (l >= r) return;

    // Swap the characters at the ends
    [res[l], res[r]] = [res[r], res[l]];

    // Recur for the remaining string
    reverseStringRec(res, l + 1, r - 1);
}

function reverseString(s) {

	// Convert string to array of characters
    let res = s.split('');  
    reverseStringRec(res, 0, res.length - 1);
    
    // Convert array back to string
    return res.join('');  
}

let s = "abdcfe";
console.log(reverseString(s));

Output
efcdba

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

Using Stack - O(n) Time and O(n) Space

The idea is to use stack for reversing a string because Stack follows Last In First Out (LIFO) principle. This means the last character you add is the first one you'll take out. So, when we push all the characters of a string into the stack, the last character becomes the first one to pop.

Illustration:


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

#include <bits/stdc++.h>
using namespace std;

string reverseString(string &s) {
    stack<char> st;
  
    // Push the charcters into stack
    for (int i = 0; i < s.size(); i++) {
        st.push(s[i]);
    }

    // Pop the characters of stack into the original string
    for (int i = 0; i < s.size(); i++) {
        s[i] = st.top();
        st.pop();
    }
  
  	return s;
}

int main() {
    string s = "abdcfe";
    cout << reverseString(s);
    return 0;
}
Java
// Java program to reverse a string using stack
import java.util.*;

class GfG {
    static String reverseString(String s) {
        Stack<Character> st = new Stack<>();
      
        // Push the characters into stack
        for (int i = 0; i < s.length(); i++)
            st.push(s.charAt(i));

        StringBuilder res = new StringBuilder();
      
        // Pop the characters of stack into the original string
        for (int i = 0; i < s.length(); i++)
            res.append(st.pop());
        
        return res.toString();
    }

    public static void main(String[] args) {
        String s = "abdcfe";
        System.out.println(reverseString(s));
    }
}
Python
# Python program to reverse a string using stack
def reverseString(s):
    stack = []
    
    # Push the characters into stack
    for char in s:
        stack.append(char)

    # Prepare a list to hold the reversed characters
    rev = [''] * len(s)

    # Pop the characters from stack into the reversed list
    for i in range(len(s)):
        rev[i] = stack.pop()

    # Join the list to form the reversed string
    return ''.join(rev)

if __name__ == "__main__":
    s = "abdcfe"
    print(reverseString(s))
C#
// C# program to reverse a string using stack

using System;
using System.Collections.Generic;
using System.Text;

class GfG {
    static string reverseString(string s) {
        Stack<char> st = new Stack<char>();

        // Push the characters into stack
        for (int i = 0; i < s.Length; i++)
            st.Push(s[i]);

        // Create a StringBuilder to hold the reversed string
        StringBuilder res = new StringBuilder();

        // Pop the characters from stack into the StringBuilder
        while (st.Count > 0)
            res.Append(st.Pop());

        // Convert the StringBuilder back to a string
        return res.ToString();
    }

    static void Main() {
        string s = "abdcfe";
        Console.WriteLine(reverseString(s));
    }
}
JavaScript
// JavaScript program to reverse a string using stack

function reverseString(s) {

    // To store the characters of the original string.
    const stack = [];

    // Push the characters into the stack.
    for (let i = 0; i < s.length; i++) {
        stack.push(s[i]);
    }

    // Create an array to hold the reversed characters
    const res = new Array(s.length);
	
    // Pop the characters of the stack and store in the array
    for (let i = 0; i < s.length; i++) {
        res[i] = stack.pop();
    }

    // Join the array to form the reversed string
    return res.join('');
}

let str = "abdcfe";
console.log(reverseString(str));

Output
efcdba

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

Using Inbuilt methods - O(n) Time and O(1) Space

The idea is to use built-in reverse method to reverse the string. If built-in method for string reversal does not exist, then convert string to array or list and use their built-in method for reverse. Then convert it back to string.

C++
#include <bits/stdc++.h>
using namespace std;

string reverseString(string &s) {
    reverse(s.begin(), s.end());
  	return s;
}

int main() {
    string s = "abdcfe"; 
    cout << reverseString(s) ;
    return 0;
} 
Java
// Java program to reverse a string using StringBuffer class

import java.io.*;
import java.util.*;

class GFG {
    static String stringReverse(String s) {
    	StringBuilder res = new StringBuilder(s);
        res.reverse();
      	return res.toString();
    }
  	
    public static void main(String[] args) {
        String s = "abdcfe";
        System.out.println(stringReverse(s));
    }
}
Python
# Function to reverse a string
def reverseString(s):
  	
    # Reverse the string using slicing
    return s[::-1]

if __name__ == "__main__":
    str = "abdcfe"
    print(reverseString(str))
C#
// C# program to reverse a string
using System;

class GfG {
    static string reverseString(string s) {
      	
        // Reverse the string using the built-in method
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }

    static void Main() {
        string s = "abdcfe"; 
        Console.WriteLine(reverseString(s));
    }
}
JavaScript
// Function to reverse a string
function reverseString(s) {
	
    // convert to array to make it mutable
	s = s.split('');
    
    // Reverse the string using the built-in method
    s = s.reverse();
    return s.join('');
}

let str = "abdcfe"; 
console.log(reverseString(str));

Output
efcdba

Time Complexity: O(n)
Auxiliary Space: O(1) in C++ and python and O(n) in Java, C# and JavaScript (extra space is used to store in array or list or StringBuilder for reversal).


Next Article
Left Rotation of a String
author
kartik
Improve
Article Tags :
  • Misc
  • Strings
  • DSA
  • Reverse
Practice Tags :
  • Misc
  • Reverse
  • Strings

Similar Reads

  • String in Data Structure
    A string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
    3 min read
  • Introduction to Strings - Data Structure and Algorithm Tutorials
    Strings are sequences of characters. The differences between a character array and a string are, a string is terminated with a special character ‘\0’ and strings are typically immutable in most of the programming languages like Java, Python and JavaScript. Below are some examples of strings:"geeks"
    7 min read
  • Applications, Advantages and Disadvantages of String
    The String data structure is the backbone of programming languages and the building blocks of communication. String data structures are one of the most fundamental and widely used tools in computer science and programming. They allow for the representation and manipulation of text and character sequ
    6 min read
  • Subsequence and Substring
    What is a Substring? A substring is a contiguous part of a string, i.e., a string inside another string. In general, for an string of size n, there are n*(n+1)/2 non-empty substrings. For example, Consider the string "geeks", There are 15 non-empty substrings. The subarrays are: g, ge, gee, geek, ge
    6 min read
  • Storage for Strings in C
    In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays C char str[4] = "GfG"; /*One extra for string terminator*/ /* OR */ char str[4] = {‘G’, ‘f’, ‘G’, '\0'}; /* '\0' is string terminator */ When strings are declared as character arra
    5 min read
  • Strings in different language

    • Strings in C
      A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is work as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'.DeclarationDeclaring a string in C i
      5 min read

    • std::string class in C++
      C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.String vs Character ArrayStringChar
      8 min read

    • String Class in Java
      A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
      7 min read

    • Python String
      A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
      6 min read

    • C# Strings
      In C#, a string is a sequence of Unicode characters or an array of characters. The range of Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed as the text. So the string is the representation of the text. A string is an important concept, and sometimes people get con
      7 min read

    • JavaScript String Methods
      JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. The following are methods that we can call on strings.slice() extra
      11 min read

    • PHP Strings
      In PHP, strings are one of the most commonly used data types. A string is a sequence of characters used to represent text, such as words and sentences. Strings are enclosed in either single quotes (' ') or double quotes (" "). You can create a string using single quotes (' ') or double quotes (" ").
      4 min read

    Basic operations on String

    • Searching For Characters and Substring in a String in Java
      Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java.Searching for a Character in a
      5 min read

    • Reverse a String – Complete Tutorial
      Given a string s, the task is to reverse the string. Reversing a string means rearranging the characters such that the first character becomes the last, the second character becomes second last and so on.Examples:Input: s = "GeeksforGeeks"Output: "skeeGrofskeeG"Explanation : The first character G mo
      13 min read

    • Left Rotation of a String
      Given a string s and an integer d, the task is to left rotate the string by d positions.Examples:Input: s = "GeeksforGeeks", d = 2Output: "eksforGeeksGe" Explanation: After the first rotation, string s becomes "eeksforGeeksG" and after the second rotation, it becomes "eksforGeeksGe".Input: s = "qwer
      15+ min read

    • Sort string of characters
      Given a string of lowercase characters from 'a' - 'z'. We need to write a program to print the characters of this string in sorted order.Examples: Input : "dcab" Output : "abcd"Input : "geeksforgeeks"Output : "eeeefggkkorss"Naive Approach - O(n Log n) TimeA simple approach is to use sorting algorith
      5 min read

    • Frequency of Characters in Alphabetical Order
      Given a string s, the task is to print the frequency of each of the characters of s in alphabetical order.Example: Input: s = "aabccccddd" Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: s = "geeksforgeeks" Output: e4
      9 min read

    • Swap characters in a String
      Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
      14 min read

    • C Program to Find the Length of a String
      The length of a string is the number of characters in it without including the null character (‘\0’). In this article, we will learn how to find the length of a string in C.The easiest way to find the string length is by using strlen() function from the C strings library. Let's take a look at an exa
      2 min read

    • How to insert characters in a string at a certain position?
      Given a string str and an array of indices chars[] that describes the indices in the original string where the characters will be added. For this post, let the character to be inserted in star (*). Each star should be inserted before the character at the given index. Return the modified string after
      7 min read

    • Check if two strings are same or not
      Given two strings, the task is to check if these two strings are identical(same) or not. Consider case sensitivity.Examples:Input: s1 = "abc", s2 = "abc" Output: Yes Input: s1 = "", s2 = "" Output: Yes Input: s1 = "GeeksforGeeks", s2 = "Geeks" Output: No Approach - By Using (==) in C++/Python/C#, eq
      7 min read

    • Concatenating Two Strings in C
      Concatenating two strings means appending one string at the end of another string. In this article, we will learn how to concatenate two strings in C.The most straightforward method to concatenate two strings is by using strcat() function. Let's take a look at an example:C#include <stdio.h> #i
      2 min read

    • Remove all occurrences of a character in a string
      Given a string and a character, remove all the occurrences of the character in the string.Examples: Input : s = "geeksforgeeks" c = 'e'Output : s = "gksforgks"Input : s = "geeksforgeeks" c = 'g'Output : s = "eeksforeeks"Input : s = "geeksforgeeks" c = 'k'Output : s = "geesforgees"Using Built-In Meth
      2 min read

    Binary String

    • Check if all bits can be made same by single flip
      Given a binary string, find if it is possible to make all its digits equal (either all 0's or all 1's) by flipping exactly one bit. Input: 101Output: YeExplanation: In 101, the 0 can be flipped to make it all 1Input: 11Output: NoExplanation: No matter whichever digit you flip, you will not get the d
      5 min read

    • Number of flips to make binary string alternate | Set 1
      Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped. Examples : Input : str = “001” Output : 1 Minimum number of flips required = 1 We can flip
      8 min read

    • Binary representation of next number
      Given a binary string that represents binary representation of positive number n, the task is to find the binary representation of n+1. The binary input may or may not fit in an integer, so we need to return a string.Examples: Input: s = "10011"Output: "10100"Explanation: Here n = (19)10 = (10011)2n
      6 min read

    • Min flips of continuous characters to make all characters same in a string
      Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110Output : 2We need to convert 1's sequenceso string consist of all 0's.Input
      8 min read

    • Generate all binary strings without consecutive 1's
      Given an integer n, the task is to generate all binary strings of size n without consecutive 1's.Examples: Input : n = 4Output : 0000 0001 0010 0100 0101 1000 1001 1010Input : n = 3Output : 000 001 010 100 101Approach:The idea is to generate all binary strings of length n without consecutive 1's usi
      6 min read

    • Find i'th Index character in a binary string obtained after n iterations
      Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes "01" and 1 becomes "10". Find the (based on indexing) index character in the string after the nth iteration. Examples: Input : m = 5, n = 2, i = 3Output : 1Input : m = 3, n = 3, i = 6Output
      6 min read

    Substring and Subsequence

    • All substrings of a given String
      Given a string s, containing lowercase alphabetical characters. The task is to print all non-empty substrings of the given string.Examples : Input : s = "abc"Output : "a", "ab", "abc", "b", "bc", "c"Input : s = "ab"Output : "a", "ab", "b"Input : s = "a"Output : "a"[Expected Approach] - Using Iterati
      8 min read

    • Print all subsequences of a string
      Given a string, we have to find out all its subsequences of it. A String is said to be a subsequence of another String, if it can be obtained by deleting 0 or more character without changing its order.Examples: Input : abOutput : "", "a", "b", "ab"Input : abcOutput : "", "a", "b", "c", "ab", "ac", "
      12 min read

    • Count Distinct Subsequences
      Given a string str of length n, your task is to find the count of distinct subsequences of it.Examples: Input: str = "gfg"Output: 7Explanation: The seven distinct subsequences are "", "g", "f", "gf", "fg", "gg" and "gfg" Input: str = "ggg"Output: 4Explanation: The four distinct subsequences are "",
      13 min read

    • Count distinct occurrences as a subsequence
      Given two strings pat and txt, where pat is always shorter than txt, count the distinct occurrences of pat as a subsequence in txt.Examples: Input: txt = abba, pat = abaOutput: 2Explanation: pat appears in txt as below three subsequences.[abba], [abba]Input: txt = banana, pat = banOutput: 3Explanati
      15+ min read

    • Longest Common Subsequence (LCS)
      Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
      15+ min read

    • Shortest Superstring Problem
      Given a set of n strings arr[], find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string.Examples: Input: arr[] = {"geeks", "quiz", "for"}Output: geeksquizforExplanation: "geeksquizfor" contains all the thr
      15+ min read

    • Printing Shortest Common Supersequence
      Given two strings s1 and s2, find the shortest string which has both s1 and s2 as its sub-sequences. If multiple shortest super-sequence exists, print any one of them.Examples:Input: s1 = "geek", s2 = "eke"Output: geekeExplanation: String "geeke" has both string "geek" and "eke" as subsequences.Inpu
      9 min read

    • Shortest Common Supersequence
      Given two strings s1 and s2, the task is to find the length of the shortest string that has both s1 and s2 as subsequences.Examples: Input: s1 = "geek", s2 = "eke"Output: 5Explanation: String "geeke" has both string "geek" and "eke" as subsequences.Input: s1 = "AGGTAB", s2 = "GXTXAYB"Output: 9Explan
      15+ min read

    • Longest Repeating Subsequence
      Given a string s, the task is to find the length of the longest repeating subsequence, such that the two subsequences don't have the same string character at the same position, i.e. any ith character in the two subsequences shouldn't have the same index in the original string. Examples:Input: s= "ab
      15+ min read

    • Longest Palindromic Subsequence (LPS)
      Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Longest Palindromic SubsequenceExamples:Input: s = "bbabcbcab"Output: 7Explanation: Subsequen
      15+ min read

    • Longest Palindromic Substring
      Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first appearing substring.Examples:Input: s = "forgeeksskeegfor" Output: "geeksskeeg"Explanation: There are several possible palindromic substrings like "kssk", "ss", "ee
      12 min read

    Palindrome

    • C Program to Check for Palindrome String
      A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program.The simplest method to check for palindrome string is to reverse the given string and store it in a temp
      4 min read

    • Check if a given string is a rotation of a palindrome
      Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
      15+ min read

    • Check if characters of a given string can be rearranged to form a palindrome
      Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
      14 min read

    • Online algorithm for checking palindrome in a stream
      Given a stream of characters (characters are received one by one), write a function that prints 'Yes' if a character makes the complete string palindrome, else prints 'No'. Examples:Input: str[] = "abcba"Output: a Yes // "a" is palindrome b No // "ab" is not palindrome c No // "abc" is not palindrom
      15+ min read

    • Print all Palindromic Partitions of a String using Bit Manipulation
      Given a string, find all possible palindromic partitions of a given string. Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions. Example: Input: nitinOut
      10 min read

    • Minimum Characters to Add at Front for Palindrome
      Given a string s, the task is to find the minimum number of characters to be added to the front of s to make it palindrome. A palindrome string is a sequence of characters that reads the same forward and backward. Examples: Input: s = "abc"Output: 2Explanation: We can make above string palindrome as
      12 min read

    • Make largest palindrome by changing at most K-digits
      You are given a string s consisting of digits (0-9) and an integer k. Convert the string into a palindrome by changing at most k digits. If multiple palindromes are possible, return the lexicographically largest one. If it's impossible to form a palindrome with k changes, return "Not Possible".Examp
      14 min read

    • Minimum Deletions to Make a String Palindrome
      Given a string s of length n, the task is to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome. Note: The order of characters should be maintained. Examples : Input : s = "aebcbda"Output : 2Explanation: Remove characters 'e' and 'd'. Resul
      15+ min read

    • Minimum insertions to form a palindrome with permutations allowed
      Given a string of lowercase letters. Find minimum characters to be inserted in the string so that it can become palindrome. We can change the positions of characters in the string.Examples: Input: geeksforgeeksOutput: 2Explanation: geeksforgeeks can be changed as: geeksroforskeeg or geeksorfroskeeg
      5 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences