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), g(1 time), k(1 time) and
s(1 time).
Hence the lexicographical output is "eegks"
Input :
string1 : hhhhhello
string2 : gfghhmh
Output : hhh
This problem has existing solution please refer Print common characters of two Strings in alphabetical order link. We will solve this problem in python using intersection property and collections.Counter() module. Approach is simple,
- Convert both strings into dictionary data type using Counter(str) method, which contains characters of string as key and their frequencies as value.
- Now find common elements between two strings using intersection ( a&b ) property.
- Resultant will also be an counter dictionary having common elements as keys and their common frequencies as value.
- Use elements() method of counter dictionary to expand list of keys by their frequency number of times.
- Sort the list and concatenate each character of output list without space to print resultant string.
Implementation:
Python3
from collections import Counter
def common(str1,str2):
dict1 = Counter(str1)
dict2 = Counter(str2)
commonDict = dict1 & dict2
if len (commonDict) = = 0 :
print ( - 1 )
return
commonChars = list (commonDict.elements())
commonChars = sorted (commonChars)
print (''.join(commonChars))
if __name__ = = "__main__" :
str1 = 'geeks'
str2 = 'forgeeks'
common(str1, str2)
|
Output:
eegks
Time complexity : O(n)
Auxiliary Space : O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
25 Jul, 2022
Like Article
Save Article