Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Print common characters of two Strings in alphabetical order
Next article icon

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

Last Updated : 25 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
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)



Next Article
Print common characters of two Strings in alphabetical order

S

Shashank Mishra
Improve
Article Tags :
  • DSA
  • Python
  • Strings
  • Python string-programs
  • python-string
Practice Tags :
  • python
  • Strings

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
    6 min read
  • Python | Check order of character in string using OrderedDict( )
    Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All
    3 min read
  • Python program to check if a string contains all unique characters
    To implement an algorithm to determine if a string contains all unique characters. Examples: Input : s = "abcd" Output: True "abcd" doesn't contain any duplicates. Hence the output is True. Input : s = "abbd" Output: False "abbd" contains duplicates. Hence the output is False. One solution is to cre
    3 min read
  • Find all duplicate characters in string in Python
    In this article, we will explore various methods to find all duplicate characters in string. The simplest approach is by using a loop with dictionary. Using Loop with DictionaryWe can use a for loop to find duplicate characters efficiently. First we count the occurrences of each character by iterati
    3 min read
  • Frequency of Characters in Alphabetical Order
    Given a string s, the task is to print the frequency of each of the characters of s in alphabetical order.Example: Input: s = "aabccccddd" Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: s = "geeksforgeeks" Output: e4
    9 min read
  • Python | Count the Number of matching characters in a pair of string
    The problem is about finding how many characters are the same in two strings. We compare the strings and count the common characters between them. In this article, we'll look at different ways to solve this problem. Using Set Sets are collections of unique items, so by converting both strings into s
    2 min read
  • Print all distinct characters of a string in order (3 Methods)
    Given a string, find the all distinct (or non-repeating characters) in it. For example, if the input string is “Geeks for Geeks”, then output should be 'for' and if input string is “Geeks Quiz”, then output should be ‘GksQuiz’.The distinct characters should be printed in same order as they appear in
    14 min read
  • Using Counter() in Python to find minimum character removal to make two strings anagram
    Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams
    3 min read
  • Convert a List of Characters into a String - Python
    Our task is to convert a list of characters into a single string. For example, if the input is ['H', 'e', 'l', 'l', 'o'], the output should be "Hello". Using join() We can convert a list of characters into a string using join() method, this method concatenates the list elements (which should be stri
    2 min read
  • Count the number of Unique Characters in a String in Python
    We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8. Using setSet in Python is an unordered collection of unique elements automatically removing d
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences