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:
string1 : geeks
string2 : forgeeks
Output : eegks
Explanation: The letters that are common between
the two strings are e(2 times), k(1 time) and
Hence the lexicographical output is "eegks"
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]).
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 email@example.com. 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.