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.
- Print all the duplicates in the input string
- Remove characters from the first string which are present in the second string
- A Program to check if strings are rotations of each other or not
- Print reverse of a string using recursion
- Write a program to print all permutations of a given string
- Print list items containing all characters of a given word
- Find the smallest window in a string containing all characters of another string
- Longest Common Subsequence | DP-4
- Length of the longest substring without repeating characters
- Check whether two strings are anagram of each other
- Print all permutations with repetition of characters
- Print all interleavings of given two strings
- Interleaving of two given strings with no common characters
- Print all permutations in sorted (lexicographic) order
- Given a sequence of words, print all anagrams together | Set 1