Reverse a String – Complete Tutorial
Last Updated :
04 Jun, 2025
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.
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));
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));
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));
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));
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));
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).
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 CA 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 JavaA 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 StringA 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# StringsIn 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 MethodsJavaScript 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 StringsIn 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 JavaEfficient 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 TutorialGiven 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 StringGiven 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 charactersGiven 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 OrderGiven 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 StringGiven 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 StringThe 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 notGiven 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 CConcatenating 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 stringGiven 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 flipGiven 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 1Given 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 numberGiven 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 stringGiven 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'sGiven 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 iterationsGiven 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 StringGiven 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 stringGiven 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 SubsequencesGiven 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 subsequenceGiven 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 ProblemGiven 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 SupersequenceGiven 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 SupersequenceGiven 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 SubsequenceGiven 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 SubstringGiven 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 StringA 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 palindromeGiven 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 palindromeGiven 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 streamGiven 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 ManipulationGiven 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 PalindromeGiven 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-digitsYou 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 PalindromeGiven 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 allowedGiven 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