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:
Replacing Characters in a String Using Dictionary in Python
Next article icon

Python counter and dictionary intersection example (Make a string using deletion and rearrangement)

Last Updated : 21 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. 

Examples:

Input : s1 = ABHISHEKsinGH       : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible  Input : s1 = Hello       : s2 = dnaKfhelddf Output : Not Possible  Input : s1 = GeeksforGeeks       : s2 = rteksfoGrdsskGeggehes Output : Possible

We have existing solution for this problem please refer Make a string from another by deletion and rearrangement of characters link. We will this problem quickly in python. Approach is very simple,

  1. Convert both string into dictionary using Counter(iterable) method, each dictionary contains characters within string as Key and their frequencies as Value.
  2. Now take intersection of two dictionaries and compare resultant output with dictionary of first string, if both are equal that means it is possible to convert string otherwise not.

Implementation:

Python3




# Python code to find if we can make first string
# from second by deleting some characters from
# second and rearranging remaining characters.
from collections import Counter
 
def makeString(str1,str2):
 
    # convert both strings into dictionaries
    # output will be like str1="aabbcc",
    # dict1={'a':2,'b':2,'c':2}
    # str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2}
    dict1 = Counter(str1)
    dict2 = Counter(str2)
 
    # take intersection of two dictionaries
    # output will be result = {'a':1,'b':2,'c':2}
    result = dict1 & dict2
 
    # compare resultant dictionary with first
    # dictionary comparison first compares keys
    # and then compares their corresponding values
    return result == dict1
 
# Driver program
if __name__ == "__main__":
    str1 = 'ABHISHEKsinGH'
    str2 = 'gfhfBHkooIHnfndSHEKsiAnG'
    if (makeString(str1,str2)==True):
        print("Possible")
    else:
        print("Not Possible")
 
 
Output
Possible

Time Complexity: O(n)

Auxiliary Space: O(1)



Next Article
Replacing Characters in a String Using Dictionary in Python

S

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

Similar Reads

  • Replacing Characters in a String Using Dictionary in Python
    In Python, we can replace characters in a string dynamically based on a dictionary. Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "Hel
    2 min read
  • Python Set Operations (Union, Intersection, Difference and Symmetric Difference)
    Sets are a fundamental data structure in Python that store unique elements. Python provides built-in operations for performing set operations such as union, intersection, difference and symmetric difference. In this article, we understand these operations one by one. Union of setsThe union of two se
    3 min read
  • How to convert a MultiDict to nested dictionary using Python
    A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested d
    3 min read
  • Python - Converting list string to dictionary
    Converting a list string to a dictionary in Python involves mapping elements from the list to key-value pairs. A common approach is pairing consecutive elements, where one element becomes the key and the next becomes the value. This results in a dictionary where each pair is represented as a key-val
    3 min read
  • Find the first repeated word in a string in Python using Dictionary
    We are given a string that may contain repeated words and the task is to find the first word that appears more than once. For example, in the string "Learn code learn fast", the word "learn" is the first repeated word. Let's understand different approaches to solve this problem using a dictionary. U
    3 min read
  • Create a Nested Dictionary from Text File Using Python
    We are given a text file and our task is to create a nested dictionary using Python. In this article, we will see how we can create a nested dictionary from a text file in Python using different approaches. Create a Nested Dictionary from Text File Using PythonBelow are the ways to Create Nested Dic
    3 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
  • Combine similar characters in Python using Dictionary Get() Method
    Let us see how to combine similar characters in a list. Example : Input : ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] Output : ['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r'] We will be using the get() method of the dictionary class. dictionary.get() The get() method returns the valu
    3 min read
  • Python dictionary, set and counter to check if frequencies can become same
    Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make th
    2 min read
  • Print anagrams together in Python using List and Dictionary
    An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. The task of grouping anagrams together in Python can be efficiently solved using lists and dictionaries. The key idea is to process each word by sorting its charac
    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