Python code to print common characters of two Strings in alphabetical order

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), 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,

  1. Convert both strings into dictionary data type using Counter(str) method, which contains characters of string as key and their frequencies as value.
  2. Now find common elements between two strings using intersection ( a&b ) property.
  3. Resultant will also be an counter dictionary having common elements as keys and their common frequencies as value.
  4. Use elements() method of counter dictionary to expand list of keys by their frequency number of times.
  5. Sort the list and concatenate each character of output list without space to print resultant string.
filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to print common characters of two Strings
# in alphabetical order
from collections import Counter
  
def common(str1,str2):
      
    # convert both strings into counter dictionary
    dict1 = Counter(str1)
    dict2 = Counter(str2)
  
    # take intersection of these dictionaries
    commonDict = dict1 & dict2
  
    if len(commonDict) == 0:
        print -1
        return
  
    # get a list of common elements
    commonChars = list(commonDict.elements())
  
    # sort list in ascending order to print resultant 
    # string on alphabetical order
    commonChars = sorted(commonChars)
   
    # join characters without space to produce 
    # resultant string
    print ''.join(commonChars)
  
# Driver program
if __name__ == "__main__":
    str1 = 'geeks'
    str2 = 'forgeeks'
    common(str1, str2)

chevron_right


Output:

eegks


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.