Decode a string recursively encoded as count followed by substring Last Updated : 24 Feb, 2025 Comments Improve Suggest changes Like Article Like Report Try it on GfG Practice An encoded string s is given, the task is to decode it. See examples to understand the pattern in which string is encoded .Examples: Input: s = "3[b2[ca]]"Output: "bcacabcacabcaca"Explanation: 1. inner substring "2[ca]" breakdown into "caca". 2. now , new string becomes "3[bcaca]" 3. similarly "3[bcaca]" becomes "bcacabcacabcaca " which is final result.Input: s = "2[ab]"Output: "abab"Input: s = "2[ab]a"Output: "ababa"Table of Content[Approach 1] Using Two Stacks - O(n) Time and O(n) Space[Approach 2] Using Single Stack - O(n) Time and O(n) Space[Alternate Approach] Without Using Stack - O(n) Time and O(n) Space[Approach 1] Using Two Stacks - O(n) Time and O(n) SpaceThe idea is to use two stacks, one for integers and another for characters. Now, traverse the string,Whenever we encounter any number, push it into the integer stack and in case of any alphabet (a to z) or open bracket ('['), push it on the character stack.Whenever any close bracket (']') is encountered, pop the characters from the character stack until open bracket ('[') is found in the stack. Also, pop the top element from the integer stack, say n. Now make a string repeating the popped character n number of time. Now, push all character of the string in the stack.After traversing whole string, integer stack will be empty and last string which will be formed will be the given result.Illustration: C++ // C++ program to decode a string recursively // encoded as count followed substring #include <iostream> #include <stack> #include <string> using namespace std; // Function to decode the pattern string 's' string decodedString(string &s) { stack<int> numStack; stack<char> charStack; string temp = ""; string res = ""; for (int i = 0; i < s.length(); i++) { int cnt = 0; // If Digit, convert it into number and // push it into integerstack. if (s[i] >= '0' && s[i] <= '9') { while (s[i] >= '0' && s[i] <= '9') { cnt = cnt * 10 + s[i] - '0'; i++; } i--; numStack.push(cnt); } // If closing bracket ']' is encountered else if (s[i] == ']') { temp = ""; cnt = numStack.top(); numStack.pop(); // pop element till opening bracket '[' is not found in the // character stack. while (charStack.top() != '[') { temp = charStack.top() + temp; charStack.pop(); } charStack.pop(); // Repeating the popped string 'temp' count number of times. for (int j = 0; j < cnt; j++) res = res.append(temp); // Push it in the character stack. for (int j = 0; j < res.length(); j++) charStack.push(res[j]); res = ""; } else charStack.push(s[i]); } // Pop all the element, make a string and return. while (!charStack.empty()) { res = charStack.top() + res; charStack.pop(); } return res; } int main() { string s = "3[b2[ca]]"; cout << decodedString(s) << endl; return 0; } Java // Java program to decode a string recursively // encoded as count followed by a substring import java.util.Stack; class GfG { // Function to decode the pattern string 's' static String decodedString(String s) { Stack<Integer> numStack = new Stack<>(); Stack<Character> charStack = new Stack<>(); String temp = ""; StringBuilder res = new StringBuilder(); for (int i = 0; i < s.length(); i++) { int cnt = 0; // If Digit, convert it into a number and // push it into the integer stack. if (Character.isDigit(s.charAt(i))) { while (Character.isDigit(s.charAt(i))) { cnt = cnt * 10 + (s.charAt(i) - '0'); i++; } i--; numStack.push(cnt); } // If closing bracket ']' is encountered else if (s.charAt(i) == ']') { temp = ""; cnt = numStack.pop(); // Pop elements till the opening bracket '[' is found // in the character stack. while (charStack.peek() != '[') { temp = charStack.pop() + temp; } charStack.pop(); // Remove '[' // Repeating the popped string 'temp' count number of times. StringBuilder repeated = new StringBuilder(); for (int j = 0; j < cnt; j++) { repeated.append(temp); } // Push it into the character stack. for (int j = 0; j < repeated.length(); j++) { charStack.push(repeated.charAt(j)); } } else { charStack.push(s.charAt(i)); } } // Pop all the elements, make a string, and return. while (!charStack.isEmpty()) { res.insert(0, charStack.pop()); } return res.toString(); } public static void main(String[] args) { String s = "3[b2[ca]]"; System.out.println(decodedString(s)); } } Python # Python program to decode a string recursively # encoded as count followed substring # Function to decode the pattern string 's' def decodedString(s): numStack = [] charStack = [] temp = "" res = "" i = 0 while i < len(s): cnt = 0 # If Digit, convert it into number and # push it into integer stack. if s[i].isdigit(): while i < len(s) and s[i].isdigit(): cnt = cnt * 10 + int(s[i]) i += 1 i -= 1 numStack.append(cnt) # If closing bracket ']' is encountered elif s[i] == ']': temp = "" cnt = numStack.pop() # Pop element till opening bracket '[' is not found # in the character stack. while charStack[-1] != '[': temp = charStack.pop() + temp charStack.pop() # Repeating the popped string 'temp' count number of times. res = temp * cnt # Push it in the character stack. for c in res: charStack.append(c) res = "" else: charStack.append(s[i]) i += 1 # Pop all the elements, make a string and return. while charStack: res = charStack.pop() + res return res if __name__ == "__main__": s = "3[b2[ca]]" print(decodedString(s)) C# // C# program to decode a string recursively // encoded as count followed by a substring using System; using System.Collections.Generic; using System.Text; class GfG { // Function to decode the pattern string 's' static string decodedString(string s) { Stack<int> numStack = new Stack<int>(); Stack<char> charStack = new Stack<char>(); string temp = ""; StringBuilder res = new StringBuilder(); for (int i = 0; i < s.Length; i++) { int cnt = 0; // If Digit, convert it into a number and // push it into the integer stack. if (char.IsDigit(s[i])) { while (char.IsDigit(s[i])) { cnt = cnt * 10 + (s[i] - '0'); i++; } i--; numStack.Push(cnt); } // If closing bracket ']' is encountered else if (s[i] == ']') { temp = ""; cnt = numStack.Pop(); // Pop elements till the opening bracket '[' is found // in the character stack. while (charStack.Peek() != '[') { temp = charStack.Pop() + temp; } charStack.Pop(); // Remove '[' // Repeating the popped string 'temp' count number of times. StringBuilder repeated = new StringBuilder(); for (int j = 0; j < cnt; j++) { repeated.Append(temp); } // Push it into the character stack. foreach (char c in repeated.ToString()) { charStack.Push(c); } } else { charStack.Push(s[i]); } } // Pop all the elements, make a string, and return. while (charStack.Count > 0) { res.Insert(0, charStack.Pop()); } return res.ToString(); } static void Main(string[] args) { string s = "3[b2[ca]]"; Console.WriteLine(decodedString(s)); } } JavaScript // JavaScript program to decode a string recursively // encoded as count followed substring function decodedString(s) { const numStack = []; const charStack = []; let temp = ""; let res = ""; for (let i = 0; i < s.length; i++) { let cnt = 0; // If Digit, convert it into number and // push it into integer stack. if (!isNaN(s[i])) { while (!isNaN(s[i])) { cnt = cnt * 10 + (s[i] - '0'); i++; } i--; numStack.push(cnt); } // If closing bracket ']' is encountered else if (s[i] === ']') { temp = ""; cnt = numStack.pop(); // Pop element till opening bracket '[' is not found // in the character stack. while (charStack[charStack.length - 1] !== '[') { temp = charStack.pop() + temp; } charStack.pop(); // Repeating the popped string 'temp' count number of times. res = temp.repeat(cnt); // Push it in the character stack. for (const c of res) { charStack.push(c); } res = ""; } else { charStack.push(s[i]); } } // Pop all the elements, make a string and return. while (charStack.length > 0) { res = charStack.pop() + res; } return res; } // Driver Code const s = "3[b2[ca]]"; console.log(decodedString(s)); Outputbcacabcacabcaca [Approach 2] Using Single Stack - O(n) Time and O(n) SpaceIn this approach, we use a single stack to store both characters and digits. Instead of maintaining a separate integer stack for storing repetition counts, we store the digits directly in the main stack. The key observation is that the number always appears before the opening bracket '['. This allows us to retrieve it later without needing an extra stack.Below are the detailed steps of implementation.Initialize an empty stack.Traverse the string:Push characters onto the stack until ']' is encountered.When ']' is found:Pop characters to form the substring until '[' is found, then remove '['.Extract the preceding number from the stack and convert it to an integer.Repeat the substring and push the expanded result back onto the stack.After traversal, pop all characters from the stack, reverse them, and return the final decoded string. C++ // C++ program to decode a string recursively encoded // as count followed substring Using Single Stack #include <iostream> #include <stack> #include <algorithm> using namespace std; string decodeString(string &s) { stack<char> st; // Traverse the input string for (int i = 0; i < s.length(); i++) { // Push characters into the stack until ']' is encountered if (s[i] != ']') { st.push(s[i]); } // Decode when ']' is found else { string temp; // Pop characters until '[' is found while (!st.empty() && st.top() != '[') { temp.push_back(st.top()); st.pop(); } reverse(temp.begin(), temp.end()); // Reverse extracted string // Remove '[' from the stack st.pop(); string num; // Extract the number (repetition count) from the stack while (!st.empty() && isdigit(st.top())) { num = st.top() + num; st.pop(); } // Convert extracted number to integer int number = stoi(num); string repeat; // Repeat the extracted string 'number' times for (int j = 0; j < number; j++) repeat.append(temp); // Push the expanded string back onto the stack for (char c : repeat) st.push(c); } } string res; // Pop all characters from stack to form the final result while (!st.empty()) { res.push_back(st.top()); st.pop(); } // Reverse to get the correct order reverse(res.begin(), res.end()); return res; } int main() { string str = "3[b2[ca]]"; cout << decodeString(str); return 0; } Java // Java program to decode a string recursively encoded // as count followed substring Using Single Stack import java.util.Stack; class GfG { static String decodeString(String s) { Stack<Character> st = new Stack<>(); // Traverse the input string for (int i = 0; i < s.length(); i++) { // Push characters into the stack until ']' is encountered if (s.charAt(i) != ']') { st.push(s.charAt(i)); } // Decode when ']' is found else { StringBuilder temp = new StringBuilder(); // Pop characters until '[' is found while (!st.isEmpty() && st.peek() != '[') { temp.append(st.pop()); } temp.reverse(); // Reverse extracted string // Remove '[' from the stack st.pop(); StringBuilder num = new StringBuilder(); // Extract the number (repetition count) from the stack while (!st.isEmpty() && Character.isDigit(st.peek())) { num.insert(0, st.pop()); } // Convert extracted number to integer int number = Integer.parseInt(num.toString()); StringBuilder repeat = new StringBuilder(); // Repeat the extracted string 'number' times for (int j = 0; j < number; j++) repeat.append(temp); // Push the expanded string back onto the stack for (char c : repeat.toString().toCharArray()) st.push(c); } } StringBuilder res = new StringBuilder(); // Pop all characters from stack to form the final result while (!st.isEmpty()) { res.append(st.pop()); } // Reverse to get the correct order res.reverse(); return res.toString(); } public static void main(String[] args) { String str = "3[b2[ca]]"; System.out.println(decodeString(str)); } } Python # python program to decode a string recursively encoded # as count followed substring Using Single Stack def decodeString(s: str) -> str: st = [] # Traverse the input string for i in range(len(s)): # Push characters into the stack until ']' is encountered if s[i] != ']': st.append(s[i]) # Decode when ']' is found else: temp = [] # Pop characters until '[' is found while st and st[-1] != '[': temp.append(st.pop()) temp.reverse() # Reverse extracted string # Remove '[' from the stack st.pop() num = [] # Extract the number (repetition count) from the stack while st and st[-1].isdigit(): num.insert(0, st.pop()) # Convert extracted number to integer number = int("".join(num)) repeat = "".join(temp) * number # Repeat the extracted string 'number' times # Push the expanded string back onto the stack st.extend(repeat) # Pop all characters from stack to form the final result return "".join(st) if __name__ == "__main__": str_val = "3[b2[ca]]" print(decodeString(str_val)) C# // C# program to decode a string recursively encoded // as count followed substring Using Single Stack using System; using System.Collections.Generic; using System.Text; class GfG { static string decodeString(string s) { Stack<char> st = new Stack<char>(); // Traverse the input string for (int i = 0; i < s.Length; i++) { // Push characters into the stack until ']' is encountered if (s[i] != ']') { st.Push(s[i]); } // Decode when ']' is found else { StringBuilder temp = new StringBuilder(); // Pop characters until '[' is found while (st.Count > 0 && st.Peek() != '[') { temp.Insert(0, st.Pop()); // Insert at beginning to simulate reverse } // Remove '[' from the stack st.Pop(); StringBuilder num = new StringBuilder(); // Extract the number (repetition count) from the stack while (st.Count > 0 && char.IsDigit(st.Peek())) { num.Insert(0, st.Pop()); } // Convert extracted number to integer int number = int.Parse(num.ToString()); StringBuilder repeat = new StringBuilder(); // Repeat the extracted string 'number' times for (int j = 0; j < number; j++) repeat.Append(temp); // Push the expanded string back onto the stack foreach (char c in repeat.ToString()) st.Push(c); } } StringBuilder res = new StringBuilder(); // Pop all characters from stack to form the final result while (st.Count > 0) { // Insert at beginning to maintain order res.Insert(0, st.Pop()); } return res.ToString(); } static void Main(string[] args) { string str = "3[b2[ca]]"; Console.WriteLine(decodeString(str)); } } JavaScript // Javascript program to decode a string recursively encoded // as count followed substring Using Single Stack function decodedString(s) { let stack = []; let temp = ""; let res = ""; for (let i = 0; i < s.length; i++) { let cnt = 0; // If number, convert it into number if (s[i] >= '0' && s[i] <= '9') { while (s[i] >= '0' && s[i] <= '9') { cnt = cnt * 10 + (s[i] - '0'); i++; } i--; // converting the integer into // char in order to store in a stack. stack.push(cnt.toString()); } // If closing bracket ']', pop element until // '[' opening bracket is not found in the // stack. else if (s[i] === ']') { temp = ""; while (stack[stack.length - 1] !== '[') { temp = stack.pop() + temp; } // Now top element of stack is '['. // Let's pop it to get the integer stack.pop(); // Top element of stack will give the integer in char form. // converting into integer. cnt = parseInt(stack.pop(), 10); // Repeating the popped string 'temp' count number of times. for (let j = 0; j < cnt; j++) { res += temp; } // Push it in the character stack. for (let j = 0; j < res.length; j++) { stack.push(res[j]); } res = ""; } else { stack.push(s[i]); } } // Pop all the element, make a string and return. while (stack.length > 0) { res = stack.pop() + res; } return res; } // Driver code const s = "3[b2[ca]]"; console.log(decodedString(s)); Outputbcacabcacabcaca[Alternate Approach] Without Using Stack - O(n) Time and O(n) SpaceThe given problem can be solved by traversing the encoded string character by character and maintaining a result string. Whenever a closing bracket is encountered, we can extract the substring enclosed within the corresponding opening bracket, and the number of times it needs to be repeated, and append the resulting string to the current result. We can continue this process until we reach the end of the input string. C++ // C++ implementation to decode the string // without using stack #include <algorithm> #include <iostream> #include <string> using namespace std; // Function to decode the given encoded string string decodedString(string &s) { // Declare a string variable to store the decoded // string string res = ""; // Traverse the encoded string character by character. for (int i = 0; i < s.length(); i++) { // If the current character is not a clostring // bracket, append it to the result string. if (s[i] != ']') { res.push_back(s[i]); } // If the current character is a closing bracket else { // Create a temporary string to store the // substring within the corresponding opening // bracket. string temp = ""; while (!res.empty() && res.back() != '[') { temp.push_back(res.back()); res.pop_back(); } // Reverse the temporary string to obtain the // correct substring. reverse(temp.begin(), temp.end()); // Remove the opening bracket from the result // string. res.pop_back(); // Extract the preceding number and convert it // to an integer. string num = ""; while (!res.empty() && res.back() >= '0' && res.back() <= '9') { num.push_back(res.back()); res.pop_back(); } reverse(num.begin(), num.end()); int p = stoi(num); // Append the substring to the result string, // repeat it to the required number of times. while (p--) { res.append(temp); } } } // Return the decoded string. return res; } int main() { string s = "3[b2[ca]]"; cout << decodedString(s); return 0; } Java // Java implementation to decode the given string without stack import java.util.*; class GfG { // Function to decode given encoded string static String decodedString(String s) { StringBuilder res = new StringBuilder(); for (int i = 0; i < s.length(); i++) { // If the current character is not a closing // bracket, append it to the result string. if (s.charAt(i) != ']') { res.append(s.charAt(i)); } // If the current character is a closing bracket else { // Create a temporary string to store // the substring within the corresponding // opening bracket. StringBuilder temp = new StringBuilder(); while (res.length() > 0 && res.charAt(res.length() - 1) != '[') { temp.insert( 0, res.charAt(res.length() - 1)); res.deleteCharAt(res.length() - 1); } // Remove the opening bracket from the // result string. res.deleteCharAt(res.length() - 1); // Extract the preceding number and convert // it to an integer. StringBuilder num = new StringBuilder(); while (res.length() > 0 && Character.isDigit( res.charAt(res.length() - 1))) { num.insert( 0, res.charAt(res.length() - 1)); res.deleteCharAt(res.length() - 1); } int p = Integer.parseInt(num.toString()); // Append the substring to the result // string, repeat it to the required number // of times. for (int j = 0; j < p; j++) { res.append(temp.toString()); } } } return res.toString(); } public static void main(String[] args) { String s = "3[b2[ca]]"; System.out.println(decodedString(s)); } } Python # Function to decode given encoded string without using stack. def decodedString(s): res = "" for i in range(len(s)): # If the current character is not a closing bracket, append it to the result string. if s[i] != ']': res += s[i] # If the current character is a closing bracket else: # Create a temporary string to store #the substring within the corresponding opening bracket. temp = "" while res and res[-1] != '[': temp = res[-1] + temp res = res[:-1] # Remove the opening bracket from the result string. res = res[:-1] # Extract the preceding number and convert it to an integer. num = "" while res and res[-1].isdigit(): num = res[-1] + num res = res[:-1] p = int(num) # Append the substring to the result #string, repeat it to the required number of times. res += temp * p return res if __name__ == "__main__": s = "3[b2[ca]]" print(decodedString(s)) C# // C# implementation to decode the string without stack using System; using System.Text; class GfG { // Function to decode the given encoded string static string decodedString(string s) { StringBuilder res = new StringBuilder(); for (int i = 0; i < s.Length; i++) { // If the current character is not a // closing bracket, append it to the result string. if (s[i] != ']') res.Append(s[i]); // If the current character is a closing bracket else { // Create a StringBuilder to store the substring // within the corresponding opening bracket. StringBuilder temp = new StringBuilder(); while (res.Length > 0 && res[res.Length - 1] != '[') { temp.Insert(0, res[res.Length - 1]); res.Length--; } // Remove the opening bracket from the result string. res.Length--; // Extract the preceding number and convert it to an integer. StringBuilder num = new StringBuilder(); while (res.Length > 0 && char.IsDigit(res[res.Length - 1])) { num.Insert(0, res[res.Length - 1]); res.Length--; } int p = int.Parse(num.ToString()); // Append the substring to the result string, // repeat it to the required number of times. for (int j = 0; j < p; j++) res.Append(temp.ToString()); } } // Return the decoded string. return res.ToString(); } static void Main(string[] args) { string s = "3[b2[ca]]"; Console.WriteLine(decodedString(s)); } } JavaScript // Function to decode the given encoded string // without using stack function decodedString(s) { let res = ""; for (let i = 0; i < s.length; i++) { // If the current character is not a closing // bracket, append it to the result string. if (s[i] !== ']') { res += s[i]; } // If the current character is a closing bracket else { // Create a temporary string to store // the substring within the corresponding opening bracket. let temp = ""; while (res.length > 0 && res[res.length - 1] !== '[') { temp = res[res.length - 1] + temp; res = res.slice(0, -1); } // Remove the opening bracket from the result string. res = res.slice(0, -1); // Extract the preceding number and convert it to an integer. let num = ""; while (res.length > 0 && !isNaN(res[res.length - 1])) { num = res[res.length - 1] + num; res = res.slice(0, -1); } let p = parseInt(num); // Append the substring to the result string, // repeat it to the required number of times. res += temp.repeat(p); } } // Return the decoded string. return res; } // Driver Code let s = "3[b2[ca]]"; console.log(decodedString(s)); Outputbcacabcacabcaca Comment More infoAdvertise with us Next Article Decode a string recursively encoded as count followed by substring kartik Follow Improve Article Tags : Strings Stack Recursion DSA Facebook +1 More Practice Tags : FacebookRecursionStackStrings 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 languageStrings 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 StringSearching 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 StringCheck 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 K'th bit in a binary representation with n iterationsGiven a decimal number m. Consider its binary representation string and apply n iterations. In each iteration, replace the character 0 with the string 01, and 1 with 10. Find the kth (1-based indexing) character in the string after the nth iterationExamples: Input: m = 5, n = 2, k = 5Output: 0Explan 15+ min read Substring and SubsequenceAll 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 PalindromeC 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 Like