Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case.
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.
1) Count occurrences of all characters from ‘a’ to ‘z’ in first and second strings. Store these counts in two arrays a1 and a2.
2) 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 implementation of above steps.
Time Complexity: If we consider n = length(larger string), then this algorithm runs in O(n) complexity.
This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Python code to print common characters of two Strings in alphabetical order
- Check if the characters of a given string are in alphabetical order
- Print the frequency of each character in Alphabetical order
- Common characters in n strings
- Interleaving of two given strings with no common characters
- Count common characters in two strings
- Check whether two strings contain same characters in same order
- Print characters having odd frequencies in order of occurrence
- Print characters having even frequencies in order of occurrence
- Print characters and their frequencies in order of occurrence
- Print characters in decreasing order of frequency
- Print characters having prime frequencies in order of occurrence
- Print all distinct characters of a string in order (3 Methods)
- Print characters and their frequencies in order of occurrence using a LinkedHashMap in Java
- Print characters and their frequencies in order of occurrence using Binary Tree