Print common characters of two Strings in alphabetical order Last Updated : 11 Jul, 2022 Summarize Comments Improve Suggest changes Share Like Article Like Report Try it on GfG Practice Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), k(1 time) and s(1 time). Hence the lexicographical output is "eegks" Input : string1 : hhhhhello string2 : gfghhmh Output : hhh The idea is to use character count arrays. Count occurrences of all characters from 'a' to 'z' in the first and second strings. Store these counts in two arrays a1[] and a2[]. Traverse a1[] and a2[] (Note size of both is 26). For every index i, print character 'a' + i number of times equal min(a1[i], a2[i]). Below is the implementation of the above steps. C++ // C++ program to print common characters // of two Strings in alphabetical order #include<bits/stdc++.h> using namespace std; int main() { string s1 = "geeksforgeeks"; string s2 = "practiceforgeeks"; // to store the count of // letters in the first string int a1[26] = {0}; // to store the count of // letters in the second string int a2[26] = {0}; int i , j; char ch; char ch1 = 'a'; int k = (int)ch1, m; // for each letter present, increment the count for(i = 0 ; i < s1.length() ; i++) { a1[(int)s1[i] - k]++; } for(i = 0 ; i < s2.length() ; i++) { a2[(int)s2[i] - k]++; } for(i = 0 ; i < 26 ; i++) { // the if condition guarantees that // the element is common, that is, // a1[i] and a2[i] are both non zero // means that the letter has occurred // at least once in both the strings if (a1[i] != 0 and a2[i] != 0) { // print the letter for a number // of times that is the minimum // of its count in s1 and s2 for(j = 0 ; j < min(a1[i] , a2[i]) ; j++) { m = k + i; ch = (char)(k + i); cout << ch; } } } return 0; } Java // Java program to print common characters // of two Strings in alphabetical order import java.io.*; import java.util.*; // Function to find similar characters public class Simstrings { static final int MAX_CHAR = 26; static void printCommon(String s1, String s2) { // two arrays of length 26 to store occurrence // of a letters alphabetically for each string int[] a1 = new int[MAX_CHAR]; int[] a2 = new int[MAX_CHAR]; int length1 = s1.length(); int length2 = s2.length(); for (int i = 0 ; i < length1 ; i++) a1[s1.charAt(i) - 'a'] += 1; for (int i = 0 ; i < length2 ; i++) a2[s2.charAt(i) - 'a'] += 1; // If a common index is non-zero, it means // that the letter corresponding to that // index is common to both strings for (int i = 0 ; i < MAX_CHAR ; i++) { if (a1[i] != 0 && a2[i] != 0) { // Find the minimum of the occurrence // of the character in both strings and print // the letter that many number of times for (int j = 0 ; j < Math.min(a1[i], a2[i]) ; j++) System.out.print(((char)(i + 'a'))); } } } // Driver code public static void main(String[] args) throws IOException { String s1 = "geeksforgeeks", s2 = "practiceforgeeks"; printCommon(s1, s2); } } Python3 # Python3 program to print common characters # of two Strings in alphabetical order # Initializing size of array MAX_CHAR=26 # Function to find similar characters def printCommon( s1, s2): # two arrays of length 26 to store occurrence # of a letters alphabetically for each string a1 = [0 for i in range(MAX_CHAR)] a2 = [0 for i in range(MAX_CHAR)] length1 = len(s1) length2 = len(s2) for i in range(0,length1): a1[ord(s1[i]) - ord('a')] += 1 for i in range(0,length2): a2[ord(s2[i]) - ord('a')] += 1 # If a common index is non-zero, it means # that the letter corresponding to that # index is common to both strings for i in range(0,MAX_CHAR): if (a1[i] != 0 and a2[i] != 0): # Find the minimum of the occurrence # of the character in both strings and print # the letter that many number of times for j in range(0,min(a1[i],a2[i])): ch = chr(ord('a')+i) print (ch, end='') # Driver code if __name__=="__main__": s1 = "geeksforgeeks" s2 = "practiceforgeeks" printCommon(s1, s2); # This Code is contributed by Abhishek Sharma C# // C# program to print common characters // of two Strings in alphabetical order using System; // Function to find similar characters public class Simstrings { static int MAX_CHAR = 26; static void printCommon(string s1, string s2) { // two arrays of length 26 to store occurrence // of a letters alphabetically for each string int[] a1 = new int[MAX_CHAR]; int[] a2 = new int[MAX_CHAR]; int length1 = s1.Length; int length2 = s2.Length; for (int i = 0 ; i < length1 ; i++) a1[s1[i] - 'a'] += 1; for (int i = 0 ; i < length2 ; i++) a2[s2[i] - 'a'] += 1; // If a common index is non-zero, it means // that the letter corresponding to that // index is common to both strings for (int i = 0 ; i < MAX_CHAR ; i++) { if (a1[i] != 0 && a2[i] != 0) { // Find the minimum of the occurrence // of the character in both strings and print // the letter that many number of times for (int j = 0 ; j < Math.Min(a1[i], a2[i]) ; j++) Console.Write(((char)(i + 'a'))); } } } // Driver code public static void Main() { string s1 = "geeksforgeeks", s2 = "practiceforgeeks"; printCommon(s1, s2); } } JavaScript <script> // Javascript program to print common characters // of two Strings in alphabetical order let MAX_CHAR = 26; // Function to find similar characters function printCommon(s1,s2) { // two arrays of length 26 to store occurrence // of a letters alphabetically for each string let a1 = new Array(MAX_CHAR); let a2 = new Array(MAX_CHAR); for(let i=0;i<MAX_CHAR;i++) { a1[i]=0; a2[i]=0; } let length1 = s1.length; let length2 = s2.length; for (let i = 0 ; i < length1 ; i++) a1[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; for (let i = 0 ; i < length2 ; i++) a2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; // If a common index is non-zero, it means // that the letter corresponding to that // index is common to both strings for (let i = 0 ; i < MAX_CHAR ; i++) { if (a1[i] != 0 && a2[i] != 0) { // Find the minimum of the occurrence // of the character in both strings and print // the letter that many number of times for (let j = 0 ; j < Math.min(a1[i], a2[i]) ; j++) document.write((String.fromCharCode(i + 'a'.charCodeAt(0)))); } } } // Driver code let s1 = "geeksforgeeks", s2 = "practiceforgeeks"; printCommon(s1, s2); // This code is contributed by avanitrachhadiya2155 </script> Outputeeefgkors Time Complexity: If we consider n = length(larger string), then this algorithm runs in O(n) complexity. Auxiliary Space: O(1). Comment More infoAdvertise with us Next Article Print common characters of two Strings in alphabetical order K kartik Follow Improve Article Tags : DSA Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 min read Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ 3 min read Like