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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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
- Find alphabetical order such that words can be considered sorted
- Reorder the position of the words in alphabetical order
- Check whether the vowels in a string are in alphabetical order or not
- Sum of the alphabetical values of the characters of a string
- Remove all non-alphabetical characters of a String in Java
- Minimum length String with Sum of the alphabetical values of the characters equal to N
- Interleaving of two given strings with no common characters
- Count common characters in two strings
- Number of common base strings for two strings
- Check whether two strings contain same characters in same order
- Common characters in n strings
- Strings formed from given characters without any consecutive repeating characters
- Check if two strings have a common substring
- Count common subsequence in two strings
- Check if there is any common character in two given strings
- Print all distinct characters of a string in order (3 Methods)
- Print characters having odd frequencies in order of occurrence