Given an array of strings words[], sorted in an alien language. Your task is to determine the correct order of letters in this alien language based on the given words. If the order is valid, return a string containing the unique letters in lexicographically increasing order as per the new language's rules.
Note: There can be multiple valid orders for a given input, so you may return any one of them. If no valid order exists due to conflicting constraints, return an empty string.
Examples:
Input: words[] = ["baa", "abcd", "abca", "cab", "cad"]
Output: "bdac"
Explanation:
The pair “baa” and “abcd” suggests ‘b’ appears before ‘a’ in the alien dictionary.
The pair “abcd” and “abca” suggests ‘d’ appears before ‘a’ in the alien dictionary.
The pair “abca” and “cab” suggests ‘a’ appears before ‘c’ in the alien dictionary.
The pair “cab” and “cad” suggests ‘b’ appears before ‘d’ in the alien dictionary.
So, ‘b’→'d’ →‘a’ →‘c’ is a valid ordering.
Input: words[] = ["caa", "aaa", "aab"]
Output: "cab"
Explanation: The pair "caa" and "aaa" suggests 'c' appears before 'a'.
The pair "aaa" and "aab" suggests 'a' appear before 'b' in the alien dictionary.
So, 'c' → 'a' → 'b' is a valid ordering.
[Approach 1] Using Kahn's algorithm
Kahn’s Algorithm is ideal for this problem because we are required to determine the order of characters in an alien language based on a sorted dictionary. This naturally forms a Directed Acyclic Graph (DAG) where an edge u -> v
means character u
comes before character v
.
Kahn's Algorithm is a BFS-based topological sort, which efficiently determines a valid linear order of nodes (characters) in a DAG. It’s particularly useful here because it handles dependencies using in-degrees, making it simple to identify characters with no prerequisites and process them in correct order. It also easily detects cycles, if a valid topological sort is not possible (e.g., cyclic dependency), it returns early.
Step-by-Step Implementation
- Initialize an adjacency list
graph[26]
, in-degree array inDegree[26]
, and existence tracker exists[26]
. - Mark characters that appear in the input words using the
exists
array. - Compare each adjacent pair of words to find the first differing character.
- Add a directed edge from the first different character of the first word to the second word’s, and increment in-degree of the latter.
- Check for invalid prefix cases where a longer word appears before its prefix (e.g., "abc" before "ab").
- Push all characters with in-degree 0 into a queue as starting nodes for BFS.
- Pop from the queue, add to result, and reduce in-degree of neighbors.
- Enqueue neighbors whose in-degree becomes 0 after reduction.
- Detect cycles by checking if all existing characters were processed (length of result).
- Return the result string if no cycle is detected; otherwise, return an empty string.
C++
#include <iostream>
#include <vector>
#include <queue>
#include <string>
using namespace std;
// Function to find the order of characters in alien dictionary
string findOrder(const vector<string>& words) {
// Adjacency list
vector<vector<int>> graph(26);
// In-degree of each character
vector<int> inDegree(26, 0);
// Tracks which characters are present
vector<bool> exists(26, false);
// Mark existing characters
for (const string& word : words) {
for (char ch : word) {
exists[ch - 'a'] = true;
}
}
// Build the graph from adjacent words
for (int i = 0; i + 1 < words.size(); ++i) {
const string& w1 = words[i];
const string& w2 = words[i + 1];
int len = min(w1.length(), w2.length());
int j = 0;
while (j < len && w1[j] == w2[j]) ++j;
if (j < len) {
int u = w1[j] - 'a';
int v = w2[j] - 'a';
graph[u].push_back(v);
inDegree[v]++;
} else if (w1.size() > w2.size()) {
// Invalid input
return "";
}
}
// Topological sort
queue<int> q;
for (int i = 0; i < 26; ++i) {
if (exists[i] && inDegree[i] == 0) {
q.push(i);
}
}
string result;
while (!q.empty()) {
int u = q.front(); q.pop();
result += (char)(u + 'a');
for (int v : graph[u]) {
inDegree[v]--;
if (inDegree[v] == 0) {
q.push(v);
}
}
}
// Check, there was a cycle or not
for (int i = 0; i < 26; ++i) {
if (exists[i] && inDegree[i] != 0) {
return "";
}
}
return result;
}
// Driver code
int main() {
vector<string> words = {"baa", "abcd", "abca", "cab", "cad"};
string order = findOrder(words);
cout<<order;
return 0;
}
Java
import java.util.*;
class GfG{
// Function to find the order of characters in alien dictionary
public static String findOrder(String[] words) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
int[] inDegree = new int[26];
boolean[] exists = new boolean[26];
// Initialize graph
for (int i = 0; i < 26; i++) {
graph.add(new ArrayList<>());
}
// Mark characters that exist in the input
for (String word : words) {
for (char ch : word.toCharArray()) {
exists[ch - 'a'] = true;
}
}
// Build the graph based on adjacent word comparisons
for (int i = 0; i < words.length - 1; i++) {
String w1 = words[i];
String w2 = words[i + 1];
int len = Math.min(w1.length(), w2.length());
int j = 0;
while (j < len && w1.charAt(j) == w2.charAt(j)) {
j++;
}
if (j < len) {
int u = w1.charAt(j) - 'a';
int v = w2.charAt(j) - 'a';
graph.get(u).add(v);
inDegree[v]++;
} else if (w1.length() > w2.length()) {
// Invalid input
return "";
}
}
// Topological Sort
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < 26; i++) {
if (exists[i] && inDegree[i] == 0) {
q.offer(i);
}
}
StringBuilder result = new StringBuilder();
while (!q.isEmpty()) {
int u = q.poll();
result.append((char) (u + 'a'));
for (int v : graph.get(u)) {
inDegree[v]--;
if (inDegree[v] == 0) {
q.offer(v);
}
}
}
// Check for cycle
for (int i = 0; i < 26; i++) {
if (exists[i] && inDegree[i] != 0) {
return "";
}
}
return result.toString();
}
public static void main(String[] args) {
String[] words = {"baa", "abcd", "abca", "cab", "cad"};
String order = findOrder(words);
System.out.print(order);
}
}
Python
from collections import deque
def findOrder(words):
# Adjacency list
graph = [[] for _ in range(26)]
# In-degree array
inDegree = [0] * 26
# To track which letters exist in input
exists = [False] * 26
# Mark existing characters
for word in words:
for ch in word:
exists[ord(ch) - ord('a')] = True
# Build graph
for i in range(len(words) - 1):
w1, w2 = words[i], words[i + 1]
minlen = min(len(w1), len(w2))
j = 0
while j < minlen and w1[j] == w2[j]:
j += 1
if j < minlen:
u = ord(w1[j]) - ord('a')
v = ord(w2[j]) - ord('a')
graph[u].append(v)
inDegree[v] += 1
elif len(w1) > len(w2):
# Invalid case
return ""
# Topological sort
q = deque([i for i in range(26) if exists[i]
and inDegree[i] == 0])
result = []
while q:
u = q.popleft()
result.append(chr(u + ord('a')))
for v in graph[u]:
inDegree[v] -= 1
if inDegree[v] == 0:
q.append(v)
if len(result) != sum(exists):
# Cycle detected or incomplete order
return ""
return ''.join(result)
# Example usage
words = ["baa", "abcd", "abca", "cab", "cad"]
order = findOrder(words)
print(order)
C#
using System;
using System.Collections.Generic;
class GfG {
public static string findOrder(string[] words) {
List<List<int>> graph = new List<List<int>>();
int[] inDegree = new int[26];
bool[] exists = new bool[26];
// Initialize graph
for (int i = 0; i < 26; i++) {
graph.Add(new List<int>());
}
// Mark existing characters
foreach (string word in words) {
foreach (char ch in word) {
exists[ch - 'a'] = true;
}
}
// Build the graph
for (int i = 0; i + 1 < words.Length; i++) {
string w1 = words[i];
string w2 = words[i + 1];
int len = Math.Min(w1.Length, w2.Length);
int j = 0;
while (j < len && w1[j] == w2[j]) j++;
if (j < len) {
int u = w1[j] - 'a';
int v = w2[j] - 'a';
graph[u].Add(v);
inDegree[v]++;
} else if (w1.Length > w2.Length) {
return "";
}
}
// Topological Sort
Queue<int> q = new Queue<int>();
for (int i = 0; i < 26; i++) {
if (exists[i] && inDegree[i] == 0) {
q.Enqueue(i);
}
}
string result = "";
while (q.Count > 0) {
int u = q.Dequeue();
result += (char)(u + 'a');
foreach (int v in graph[u]) {
inDegree[v]--;
if (inDegree[v] == 0) {
q.Enqueue(v);
}
}
}
// Check for cycle
for (int i = 0; i < 26; i++) {
if (exists[i] && inDegree[i] != 0) {
return "";
}
}
return result;
}
public static void Main() {
string[] words = {"baa", "abcd", "abca", "cab", "cad"};
string order = findOrder(words);
Console.WriteLine(order);
}
}
JavaScript
function findOrder(words) {
const graph = Array.from({ length: 26 }, () => []);
const inDegree = Array(26).fill(0);
const exists = Array(26).fill(false);
// Mark existing characters
for (const word of words) {
for (const ch of word) {
exists[ch.charCodeAt(0) - 97] = true;
}
}
// Build the graph
for (let i = 0; i < words.length - 1; i++) {
const w1 = words[i], w2 = words[i + 1];
let j = 0;
while (j < Math.min(w1.length, w2.length) && w1[j] === w2[j]) {
j++;
}
if (j < w1.length && j < w2.length) {
const u = w1.charCodeAt(j) - 97;
const v = w2.charCodeAt(j) - 97;
graph[u].push(v);
inDegree[v]++;
} else if (w1.length > w2.length) {
// Invalid input
return "";
}
}
// Topological Sort (BFS)
const q = [];
for (let i = 0; i < 26; i++) {
if (exists[i] && inDegree[i] === 0) {
q.push(i);
}
}
const result = [];
while (q.length > 0) {
const u = q.shift();
result.push(String.fromCharCode(u + 97));
for (const v of graph[u]) {
inDegree[v]--;
if (inDegree[v] === 0) {
q.push(v);
}
}
}
if (result.length !== exists.filter(x => x).length) {
// Cycle detected
return "";
}
return result.join('');
}
// Example usage
const words = ["baa", "abcd", "abca", "cab", "cad"];
const order = findOrder(words);
console.log(order);
Time Complexity: O(n * m) , where n is size of array arr[], m is the size of each string arr[i]
Auxiliary Space: O(1)
[Approach 2] Using Depth-First Search
DFS (Depth-First Search) helps us find the correct order of letters in the alien language. By looking at how the words are ordered in the alien dictionary, we can figure out which letter should come before another. DFS is useful here because it lets us go through the letters step by step, following these rules, and helps us build the final order correctly.
DFS works well because it can detect cycles in the graph (which would make a valid ordering impossible) and enables us to build the correct order of characters as we traverse the graph. Once we visit all dependencies of a character (all the characters it must come before), we can add it to the result. The DFS ensures we are not violating any character order constraints while visiting nodes and is an effective way to perform a topological sort.
C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// Depth-first search function for topological sorting and cycle detection
bool dfs(int u, vector<vector<int>> &graph, vector<int> &vis,
vector<int> &rec, string &ans) {
// Mark the node as visited and part of the current recursion stack
vis[u] = rec[u] = 1;
for (int v = 0; v < 26; v++) {
if (graph[u][v]) {
if (!vis[v]) {
// Recurse and check for cycle
if (!dfs(v, graph, vis, rec, ans))
return false;
} else if (rec[v]) {
// A cycle is detected if v is already in the current recursion stack
return false;
}
}
}
// Add the character to the result after visiting all dependencies
ans.push_back(char('a' + u));
// Remove from recursion stack
rec[u] = 0;
return true;
}
// Function to find the correct order of characters in an alien dictionary
string findOrder(vector<string> &words) {
// Adjacency matrix for character precedence
vector<vector<int>> graph(26, vector<int>(26, 0));
// Marks if a character exists in the dictionary
vector<int> exist(26, 0);
// Marks if a character has been visited
vector<int> vis(26, 0);
// Recursion stack to detect cycles
vector<int> rec(26, 0);
// Resultant character order
string ans = "";
// Step 1: Mark all characters that appear in the input
for (string word : words) {
for (char ch : word) {
exist[ch - 'a'] = 1;
}
}
//Build the graph
for (int i = 0; i + 1 < words.size(); i++) {
const string &a = words[i], &b = words[i + 1];
int n = a.size(), m = b.size(), ind = 0;
// Find the first different character between a and b
while (ind < n && ind < m && a[ind] == b[ind])
ind++;
if (ind != n && ind == m)
return "";
if (ind < n && ind < m)
graph[a[ind] - 'a'][b[ind] - 'a'] = 1;
}
for (int i = 0; i < 26; i++) {
if (exist[i] && !vis[i]) {
if (!dfs(i, graph, vis, rec, ans)) {
// Return empty string if a cycle is found
return "";
}
}
}
// Reverse to get the correct topological order
reverse(ans.begin(), ans.end());
return ans;
}
// Driver code to test the implementation
int main() {
vector<string> words = {"baa", "abcd", "abca", "cab", "cad"};
string order = findOrder(words);
if (order.empty()) {
cout << "No Ordering Possible" << endl;
} else {
cout << order << endl;
}
return 0;
}
Java
import java.util.*;
class GfG {
// Depth-first search function for topological sorting
// and cycle detection
static boolean dfs(int u, int[][] graph, int[] vis, int[] rec,
StringBuilder ans) {
// Mark as visited and add to recursion stack
vis[u] = rec[u] = 1;
for (int v = 0; v < 26; v++) {
if (graph[u][v] == 1) {
if (vis[v] == 0) {
if (!dfs(v, graph, vis, rec, ans))
return false;
} else if (rec[v] == 1) {
// Cycle detected
return false;
}
}
}
// Append after visiting dependencies
ans.append((char) ('a' + u));
// Remove from recursion stack
rec[u] = 0;
return true;
}
// Function to find the correct order of characters
// in an alien dictionary
static String findOrder(String[] words) {
int[][] graph = new int[26][26];
int[] exist = new int[26];
int[] vis = new int[26];
int[] rec = new int[26];
StringBuilder ans = new StringBuilder();
// Mark characters that appear
for (String word : words) {
for (int j = 0; j < word.length(); j++) {
char ch = word.charAt(j);
exist[ch - 'a'] = 1;
}
}
// Build the graph
for (int i = 0; i + 1 < words.length; i++) {
String a = words[i], b = words[i + 1];
int n = a.length(), m = b.length(), ind = 0;
while (ind < n && ind < m && a.charAt(ind) == b.charAt(ind))
ind++;
if (ind != n && ind == m)
// Invalid case
return "";
if (ind < n && ind < m)
graph[a.charAt(ind) - 'a'][b.charAt(ind) - 'a'] = 1;
}
for (int i = 0; i < 26; i++) {
if (exist[i] == 1 && vis[i] == 0) {
if (!dfs(i, graph, vis, rec, ans)) {
return "";
}
}
}
// Reverse to get correct order
return ans.reverse().toString();
}
public static void main(String[] args) {
String[] words = {"baa", "abcd", "abca", "cab", "cad"};
String order = findOrder(words);
if (order.isEmpty()) {
System.out.println("No Ordering Possible");
} else {
System.out.println(order);
}
}
}
Python
def dfs(u, graph, vis, rec, ans):
# Mark the node as visited and part of the current recursion stack
vis[u] = rec[u] = 1
for v in range(26):
if graph[u][v]:
if not vis[v]:
# Recurse and check for cycle
if not dfs(v, graph, vis, rec, ans):
return False
elif rec[v]:
# A cycle is detected
return False
# Add character after visiting dependencies
ans.append(chr(ord('a') + u))
rec[u] = 0 # Remove from recursion stack
return True
def findOrder(words):
# 26x26 adjacency matrix
graph = [[0 for _ in range(26)] for _ in range(26)]
exist = [0] * 26
vis = [0] * 26
rec = [0] * 26
ans = []
# Step 1: Mark all characters that appear
for word in words:
for ch in word:
exist[ord(ch) - ord('a')] = 1
# Step 2: Build graph
for i in range(len(words) - 1):
a, b = words[i], words[i + 1]
n, m = len(a), len(b)
ind = 0
while ind < n and ind < m and a[ind] == b[ind]:
ind += 1
if ind != n and ind == m:
return "" # Invalid case
if ind < n and ind < m:
graph[ord(a[ind]) - ord('a')][ord(b[ind]) - ord('a')] = 1
# Step 3: DFS
for i in range(26):
if exist[i] and not vis[i]:
if not dfs(i, graph, vis, rec, ans):
return ""
return ''.join(reversed(ans))
# Driver code
words = ["baa", "abcd", "abca", "cab", "cad"]
order = findOrder(words)
if not order:
print("No Ordering Possible")
else:
print(order)
C#
using System;
using System.Collections.Generic;
using System.Text;
class GfG{
// Depth-first search function for topological sorting and
// cycle detection
static bool dfs(int u, int[,] graph, int[] vis, int[] rec,
StringBuilder ans) {
// Mark visited and add to recursion stack
vis[u] = rec[u] = 1;
for (int v = 0; v < 26; v++) {
if (graph[u, v] == 1) {
if (vis[v] == 0) {
if (!dfs(v, graph, vis, rec, ans))
return false;
} else if (rec[v] == 1) {
// Cycle detected
return false;
}
}
}
// Add after dependencies
ans.Append((char)('a' + u));
// Remove from recursion stack
rec[u] = 0;
return true;
}
// Function to find the correct order of characters
// in an alien dictionary
static string findOrder(List<string> words) {
int[,] graph = new int[26, 26];
int[] exist = new int[26];
int[] vis = new int[26];
int[] rec = new int[26];
StringBuilder ans = new StringBuilder();
// Mark characters that appear
foreach (string word in words) {
foreach (char ch in word) {
exist[ch - 'a'] = 1;
}
}
// Build graph
for (int i = 0; i + 1 < words.Count; i++) {
string a = words[i], b = words[i + 1];
int n = a.Length, m = b.Length, ind = 0;
while (ind < n && ind < m && a[ind] == b[ind])
ind++;
if (ind != n && ind == m)
// Invalid case
return "";
if (ind < n && ind < m)
graph[a[ind] - 'a', b[ind] - 'a'] = 1;
}
for (int i = 0; i < 26; i++) {
if (exist[i] == 1 && vis[i] == 0) {
if (!dfs(i, graph, vis, rec, ans)) {
return "";
}
}
}
// Reverse to get the correct topological order
char[] charArray = ans.ToString().ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static void Main() {
List<string> words = new List<string>
{ "baa", "abcd", "abca", "cab", "cad" };
string order = findOrder(words);
if (order == "") {
Console.WriteLine("No Ordering Possible");
} else {
Console.WriteLine(order);
}
}
}
JavaScript
function dfs(u, graph, vis, rec, ans) {
// Mark visited and recursion stack
vis[u] = rec[u] = 1;
for (let v = 0; v < 26; v++) {
if (graph[u][v]) {
if (!vis[v]) {
if (!dfs(v, graph, vis, rec, ans))
return false;
} else if (rec[v]) {
// Cycle detected
return false;
}
}
}
ans.push(String.fromCharCode(97 + u));
rec[u] = 0;
return true;
}
function findOrder(words) {
let graph = Array.from({ length: 26 }, () => Array(26).fill(0));
let exist = Array(26).fill(0);
let vis = Array(26).fill(0);
let rec = Array(26).fill(0);
let ans = [];
// Mark existing characters
for (let word of words) {
for (let i = 0; i < word.length; i++) {
exist[word.charCodeAt(i) - 97] = 1;
}
}
// Build graph
for (let i = 0; i + 1 < words.length; i++) {
let a = words[i];
let b = words[i + 1];
let n = a.length, m = b.length, ind = 0;
while (ind < n && ind < m && a[ind] === b[ind])
ind++;
if (ind !== n && ind === m)
// Invalid
return "";
if (ind < n && ind < m)
graph[a.charCodeAt(ind) - 97][b.charCodeAt(ind) - 97] = 1;
}
for (let i = 0; i < 26; i++) {
if (exist[i] && !vis[i]) {
if (!dfs(i, graph, vis, rec, ans))
return "";
}
}
return ans.reverse().join('');
}
// Driver code
let words = ["baa", "abcd", "abca", "cab", "cad"];
let order = findOrder(words);
if (order === "") {
console.log("No Ordering Possible");
} else {
console.log(order);
}
Time Complexity: O(n * m) , where n is size of array arr[], m is the size of each string arr[i]
Auxiliary Space: O(1)
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