Find if an array of strings can be chained to form a circle | Set 2
Last Updated :
11 Mar, 2024
Given an array of strings, find if the given strings can be chained to form a circle. A string X can be put before another string Y in a circle if the last character of X is the same as the first character of Y.
Examples:
Input: arr[] = {"geek", "king"}
Output: Yes, the given strings can be chained.
Note that the last character of first string is same
as first character of second string and vice versa is
also true.
Input: arr[] = {"for", "geek", "rig", "kaf"}
Output: Yes, the given strings can be chained.
The strings can be chained as "for", "rig", "geek"
and "kaf"
Input: arr[] = {"aab", "bac", "aaa", "cda"}
Output: Yes, the given strings can be chained.
The strings can be chained as "aaa", "aab", "bac"
and "cda"
Input: arr[] = {"aaa", "bbb", "baa", "aab"};
Output: Yes, the given strings can be chained.
The strings can be chained as "aaa", "aab", "bbb"
and "baa"
Input: arr[] = {"aaa"};
Output: Yes
Input: arr[] = {"aaa", "bbb"};
Output: No
Input : arr[] = ["abc", "efg", "cde", "ghi", "ija"]
Output : Yes
These strings can be reordered as, “abc”, “cde”, “efg”,
“ghi”, “ija”
Input : arr[] = [“ijk”, “kji”, “abc”, “cba”]
Output : No
We strongly recommend that you practice it, before moving on to the solution.
We have discussed one approach to this problem in the below post.
Find if an array of strings can be chained to form a circle | Set 1
In this post, another approach is discussed. We solve this problem by treating this as a graph problem, where vertices will be the first and last character of strings, and we will draw an edge between two vertices if they are the first and last character of the same string, so a number of edges in the graph will be same as the number of strings in the array.
Graph representation of some string arrays are given in the below diagram,

Now it can be clearly seen after graph representation that if a loop among graph vertices is possible then we can reorder the strings otherwise not. As in the above diagram’s example, a loop can be found in the first and third array of string but not in the second array of string. Now to check whether this graph can have a loop which goes through all the vertices, we’ll check two conditions,
- Indegree and Outdegree of each vertex should be the same.
- The graph should be strongly connected.
The first condition can be checked easily by keeping two arrays, in and out for each character. For checking whether a graph is having a loop which goes through all vertices is the same as checking complete directed graph is strongly connected or not because if it has a loop which goes through all vertices then we can reach to any vertex from any other vertex that is, the graph will be strongly connected and the same argument can be given for reverse statement also.
Now for checking the second condition we will just run a DFS from any character and visit all reachable vertices from this, now if the graph has a loop then after this one DFS all vertices should be visited, if all vertices are visited then we will return true otherwise false so visiting all vertices in a single DFS flags a possible ordering among strings.
C++
// C++ code to check if cyclic order is possible among strings
// under given constraints
#include <bits/stdc++.h>
using namespace std;
#define M 26
// Utility method for a depth first search among vertices
void dfs(vector<int> g[], int u, vector<bool> &visit)
{
visit[u] = true;
for (int i = 0; i < g[u].size(); ++i)
if(!visit[g[u][i]])
dfs(g, g[u][i], visit);
}
// Returns true if all vertices are strongly connected
// i.e. can be made as loop
bool isConnected(vector<int> g[], vector<bool> &mark, int s)
{
// Initialize all vertices as not visited
vector<bool> visit(M, false);
// perform a dfs from s
dfs(g, s, visit);
// now loop through all characters
for (int i = 0; i < M; i++)
{
/* I character is marked (i.e. it was first or last
character of some string) then it should be
visited in last dfs (as for looping, graph
should be strongly connected) */
if (mark[i] && !visit[i])
return false;
}
// If we reach that means graph is connected
return true;
}
// return true if an order among strings is possible
bool possibleOrderAmongString(string arr[], int N)
{
// Create an empty graph
vector<int> g[M];
// Initialize all vertices as not marked
vector<bool> mark(M, false);
// Initialize indegree and outdegree of every
// vertex as 0.
vector<int> in(M, 0), out(M, 0);
// Process all strings one by one
for (int i = 0; i < N; i++)
{
// Find first and last characters
int f = arr[i].front() - 'a';
int l = arr[i].back() - 'a';
// Mark the characters
mark[f] = mark[l] = true;
// increase indegree and outdegree count
in[l]++;
out[f]++;
// Add an edge in graph
g[f].push_back(l);
}
// If for any character indegree is not equal to
// outdegree then ordering is not possible
for (int i = 0; i < M; i++)
if (in[i] != out[i])
return false;
return isConnected(g, mark, arr[0].front() - 'a');
}
// Driver code to test above methods
int main()
{
// string arr[] = {"abc", "efg", "cde", "ghi", "ija"};
string arr[] = {"ab", "bc", "cd", "de", "ed", "da"};
int N = sizeof(arr) / sizeof(arr[0]);
if (possibleOrderAmongString(arr, N) == false)
cout << "Ordering not possible\n";
else
cout << "Ordering is possible\n";
return 0;
}
Java
// Java code to check if cyclic order is
// possible among strings under given constraints
import java.io.*;
import java.util.*;
class GFG{
// Return true if an order among strings is possible
public static boolean possibleOrderAmongString(
String s[], int n)
{
int m = 26;
boolean mark[] = new boolean[m];
int in[] = new int[26];
int out[] = new int[26];
ArrayList<
ArrayList<Integer>> adj = new ArrayList<
ArrayList<Integer>>();
for(int i = 0; i < m; i++)
adj.add(new ArrayList<>());
// Process all strings one by one
for(int i = 0; i < n; i++)
{
// Find first and last characters
int f = (int)(s[i].charAt(0) - 'a');
int l = (int)(s[i].charAt(
s[i].length() - 1) - 'a');
// Mark the characters
mark[f] = mark[l] = true;
// Increase indegree and outdegree count
in[l]++;
out[f]++;
// Add an edge in graph
adj.get(f).add(l);
}
// If for any character indegree is not equal to
// outdegree then ordering is not possible
for(int i = 0; i < m; i++)
{
if (in[i] != out[i])
return false;
}
return isConnected(adj, mark,
s[0].charAt(0) - 'a');
}
// Returns true if all vertices are strongly
// connected i.e. can be made as loop
public static boolean isConnected(
ArrayList<ArrayList<Integer>> adj,
boolean mark[], int src)
{
boolean visited[] = new boolean[26];
// Perform a dfs from src
dfs(adj, visited, src);
for(int i = 0; i < 26; i++)
{
/* I character is marked (i.e. it was first or
last character of some string) then it should
be visited in last dfs (as for looping, graph
should be strongly connected) */
if (mark[i] && !visited[i])
return false;
}
// If we reach that means graph is connected
return true;
}
// Utility method for a depth first
// search among vertices
public static void dfs(ArrayList<ArrayList<Integer>> adj,
boolean visited[], int src)
{
visited[src] = true;
for(int i = 0; i < adj.get(src).size(); i++)
if (!visited[adj.get(src).get(i)])
dfs(adj, visited, adj.get(src).get(i));
}
// Driver code
public static void main(String[] args)
{
String s[] = { "ab", "bc", "cd", "de", "ed", "da" };
int n = s.length;
if (possibleOrderAmongString(s, n))
System.out.println("Ordering is possible");
else
System.out.println("Ordering is not possible");
}
}
// This code is contributed by parascoding
Python3
# Python3 code to check if
# cyclic order is possible
# among strings under given
# constraints
M = 26
# Utility method for a depth
# first search among vertices
def dfs(g, u, visit):
visit[u] = True
for i in range(len(g[u])):
if(not visit[g[u][i]]):
dfs(g, g[u][i], visit)
# Returns true if all vertices
# are strongly connected i.e.
# can be made as loop
def isConnected(g, mark, s):
# Initialize all vertices
# as not visited
visit = [False for i in range(M)]
# Perform a dfs from s
dfs(g, s, visit)
# Now loop through
# all characters
for i in range(M):
# I character is marked
# (i.e. it was first or last
# character of some string)
# then it should be visited
# in last dfs (as for looping,
# graph should be strongly
# connected) */
if(mark[i] and (not visit[i])):
return False
# If we reach that means
# graph is connected
return True
# return true if an order among
# strings is possible
def possibleOrderAmongString(arr, N):
# Create an empty graph
g = {}
# Initialize all vertices
# as not marked
mark = [False for i in range(M)]
# Initialize indegree and
# outdegree of every
# vertex as 0.
In = [0 for i in range(M)]
out = [0 for i in range(M)]
# Process all strings
# one by one
for i in range(N):
# Find first and last
# characters
f = (ord(arr[i][0]) -
ord('a'))
l = (ord(arr[i][-1]) -
ord('a'))
# Mark the characters
mark[f] = True
mark[l] = True
# Increase indegree
# and outdegree count
In[l] += 1
out[f] += 1
if f not in g:
g[f] = []
# Add an edge in graph
g[f].append(l)
# If for any character
# indegree is not equal to
# outdegree then ordering
# is not possible
for i in range(M):
if(In[i] != out[i]):
return False
return isConnected(g, mark,
ord(arr[0][0]) -
ord('a'))
# Driver code
arr = ["ab", "bc",
"cd", "de",
"ed", "da"]
N = len(arr)
if(possibleOrderAmongString(arr, N) ==
False):
print("Ordering not possible")
else:
print("Ordering is possible")
# This code is contributed by avanitrachhadiya2155
C#
// C# code to check if cyclic order is
// possible among strings under given constraints
using System;
using System.Collections.Generic;
class GFG {
// Return true if an order among strings is possible
static bool possibleOrderAmongString(string[] s, int n)
{
int m = 26;
bool[] mark = new bool[m];
int[] In = new int[26];
int[] Out = new int[26];
List<List<int>> adj = new List<List<int>>();
for(int i = 0; i < m; i++)
adj.Add(new List<int>());
// Process all strings one by one
for(int i = 0; i < n; i++)
{
// Find first and last characters
int f = (int)(s[i][0] - 'a');
int l = (int)(s[i][s[i].Length - 1] - 'a');
// Mark the characters
mark[f] = mark[l] = true;
// Increase indegree and outdegree count
In[l]++;
Out[f]++;
// Add an edge in graph
adj[f].Add(l);
}
// If for any character indegree is not equal to
// outdegree then ordering is not possible
for(int i = 0; i < m; i++)
{
if (In[i] != Out[i])
return false;
}
return isConnected(adj, mark,
s[0][0] - 'a');
}
// Returns true if all vertices are strongly
// connected i.e. can be made as loop
public static bool isConnected(
List<List<int>> adj,
bool[] mark, int src)
{
bool[] visited = new bool[26];
// Perform a dfs from src
dfs(adj, visited, src);
for(int i = 0; i < 26; i++)
{
/* I character is marked (i.e. it was first or
last character of some string) then it should
be visited in last dfs (as for looping, graph
should be strongly connected) */
if (mark[i] && !visited[i])
return false;
}
// If we reach that means graph is connected
return true;
}
// Utility method for a depth first
// search among vertices
public static void dfs(List<List<int>> adj,
bool[] visited, int src)
{
visited[src] = true;
for(int i = 0; i < adj[src].Count; i++)
if (!visited[adj[src][i]])
dfs(adj, visited, adj[src][i]);
}
static void Main() {
string[] s = { "ab", "bc", "cd", "de", "ed", "da" };
int n = s.Length;
if (possibleOrderAmongString(s, n))
Console.Write("Ordering is possible");
else
Console.Write("Ordering is not possible");
}
}
// This code is contributed by divyesh072019.
JavaScript
<script>
// Javascript code to check if cyclic order is
// possible among strings under given constraints
// Return true if an order among strings is possible
function possibleOrderAmongString(s, n)
{
let m = 26;
let mark = new Array(m);
mark.fill(false);
let In = new Array(26);
In.fill(0);
let Out = new Array(26);
Out.fill(0);
let adj = [];
for(let i = 0; i < m; i++)
adj.push([]);
// Process all strings one by one
for(let i = 0; i < n; i++)
{
// Find first and last characters
let f = (s[i][0].charCodeAt() - 'a'.charCodeAt());
let l = (s[i][s[i].length - 1].charCodeAt() - 'a'.charCodeAt());
// Mark the characters
mark[f] = mark[l] = true;
// Increase indegree and outdegree count
In[l]++;
Out[f]++;
// Add an edge in graph
adj[f].push(l);
}
// If for any character indegree is not equal to
// outdegree then ordering is not possible
for(let i = 0; i < m; i++)
{
if (In[i] != Out[i])
return false;
}
return isConnected(adj, mark, s[0][0].charCodeAt() - 'a'.charCodeAt());
}
// Returns true if all vertices are strongly
// connected i.e. can be made as loop
function isConnected(adj, mark, src)
{
let visited = new Array(26);
visited.fill(false);
// Perform a dfs from src
dfs(adj, visited, src);
for(let i = 0; i < 26; i++)
{
/* I character is marked (i.e. it was first or
last character of some string) then it should
be visited in last dfs (as for looping, graph
should be strongly connected) */
if (mark[i] && !visited[i])
return false;
}
// If we reach that means graph is connected
return true;
}
// Utility method for a depth first
// search among vertices
function dfs(adj, visited, src)
{
visited[src] = true;
for(let i = 0; i < adj[src].length; i++)
if (!visited[adj[src][i]])
dfs(adj, visited, adj[src][i]);
}
let s = [ "ab", "bc", "cd", "de", "ed", "da" ];
let n = s.length;
if (possibleOrderAmongString(s, n))
document.write("Ordering is possible");
else
document.write("Ordering is not possible");
// This code is contributed by decode2207.
</script>
OutputOrdering is possible
Time complexity: O(n)
Auxiliary Space: O(n)
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