Open In App

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

Last Updated : 25 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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,

  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.

Implementation:

Python3




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


Output:

eegks

Time complexity : O(n) 
Auxiliary Space : O(n)


Similar Reads

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 out
6 min read
Python - Extract Strings with Successive Alphabets in Alphabetical Order
Given a string list, extract list which has any succession of characters as they occur in alphabetical order. Input : test_list = ['gfg', 'ij', 'best', 'for', 'geeks'] Output : ['ij', 'gfg', 'best'] Explanation : i-j, f-g, s-t are consecutive pairs. Input : test_list = ['gf1g', 'in', 'besht', 'for', 'geeks'] Output : [] Explanation : No consecutive
5 min read
Check if the characters of a given string are in alphabetical order
Given a string 's', the task is to find if the characters of the string are in alphabetical order. The string contains only lowercase characters. Examples: Input: Str = "aabbbcc" Output: In alphabetical order Input: Str = "aabbbcca" Output: Not in alphabetical order A simple approach: Store the string to a character array and sort the array.If the
14 min read
Find the sum of alphabetical order of characters in a string
Given string S of size N, the task is to find the sum of the alphabet value of each character in the given string. Examples: Input: S = “geek” Output: 28 Explanation:The value obtained by the sum order of alphabets is 7 + 5 + 5 + 11 = 28. Input: S = “GeeksforGeeks” Output: 133 Approach: Traverse all the characters present in the given string S.For
3 min read
Sort the array of strings according to alphabetical order defined by another string
Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str. Note: str and every string in strArr[] consists of only lower case alphabets. Examples: Input: str = "fguecbdavwyxzhijklmnopqrst", strArr[] = {"geeksforgeeks", "is", "the", "best", "place", "for", "learning"} Output
5 min read
Check if alphabetical order sum of given strings are equal or not
Given two strings s1 and s2, the task is to check if the alphabetical order sum of characters of two given strings are equal or notExamples: Input: s1= "geek", s2="abcdefg"Output: TrueExplanation: Alphabetical order sum of characters of both the strings are: s1= 7+5+5+11 = 28s2= 1+2+3+4+5+6+7 = 28 Input: s1= "bad", s2="good"Output: False Approach:
8 min read
Print the frequency of each character in Alphabetical order
Given a string str, the task is to print the frequency of each of the characters of str in alphabetical order.Example: Input: str = "aabccccddd" Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: str = "geeksforgeeks" Output: e4f1g2k2o1r1s2 Approach: Create a Map to sto
10 min read
Python Program to Sort Words in Alphabetical Order
Given an input string, our task is to write a program to sort the words in alphabetic order using Python. Examples: Input : "geeks for Geeks" Output : "for geeks geeks" Input : "the Quick brown fox jumPs over the lazY Dog" Output : "brown dog fox jumps lazy over quick the the" Sort Words in Alphabetic Order using sorted() Python sorted() is a prede
3 min read
Find alphabetical order such that words can be considered sorted
Given an array of words, find any alphabetical order in the English alphabet such that the given words can be considered sorted (increasing), if there exists such an order, otherwise output impossible. Examples: Input : words[] = {"zy", "ab"} Output : zabcdefghijklmnopqrstuvwxy Basically we need to make sure that 'z' comes before 'a'. Input : words
15 min read
Check whether the vowels in a string are in alphabetical order or not
Given a string 'str', the task is to find whether the vowels in the string are in alphabetical order or not. The string contains only lowercase alphabets. Examples: Input: str = "aabbbddeecc" Output: Vowels are in alphabetical order The vowel characters in the string are : a, a, e, e which are in sorted order. Input: str = "aabbbdideecc" Output: Vo
9 min read
Practice Tags :
three90RightbarBannerImg