The Wayback Machine - https://web.archive.org/web/20240909161837/https://www.geeksforgeeks.org/python-counter-dictionary-intersection-example-make-string-using-deletion-rearrangement/
Open In App

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
Save
Share
Report
News Follow

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)



Similar Reads

Python - Counter.items(), Counter.keys() and Counter.values()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It imp
3 min read
Make a string from another by deletion and rearrangement of characters
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 = gfhfBHkooIHnfndSHEKsiAnGOutput : Possible Input : s1 = Hello, s2 = dnaKfhelddfOutput : Not Possible Input : s1 = GeeksforGeeks, s2 = rteksfoGrdsskGeggehesOutput : Po
5 min read
Minimize swaps of adjacent characters to sort every possible rearrangement of given Binary String
Given a binary string S of length N consisting of 0s, 1s, and "?", where "?" can be replaced by either 0 or 1, the task is to count the sum of minimum swaps of adjacent characters required to sort every possible arrangement of the string in non-decreasing order Since the answer can be very large, print it modulo 109 + 7. Examples: Input: S = "?0?"O
9 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 the frequency of each character same. Input : str =
2 min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
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. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Maximize the Median of Array formed from adjacent maximum of a rearrangement
You are given X[] of length 2*N, Where N will always be odd, the task is to construct an array Y[] of length N from a rearrangement of X[] such that Y[]'s element is equal to max(Xi, Xi+1) and i is always an even index (0 based indexing), and the median of the new array is maximum possible. Examples: Input: N = 1, X[] = {1, 2} Output: X[] = {2, 1},
6 min read
Maximise product of each array element with their indices by rearrangement
Given an Array of N integers, the task is to maximize the value of the product of each array element with their corresponding indices by rearranging the array. Examples: Input: N = 4, arr[] = { 3, 5, 6, 1 }Output: 31Explanation: If we arrange arr[] as { 1, 3, 5, 6 }. Sum of arr[i]*i is 1*0 + 3*1 + 5*2 + 6*3 = 31, which is maximum Input: N = 2, arr[
4 min read
Rearrangement of a number which is also divisible by it
Given a number n, we need to rearrange all its digits such that the new arrangement is divisible by n. Also, the new number should not be equal to x. If no such rearrangement is possible, print -1. Examples: Input : n = 1035 Output : 3105 The result 3105 is divisible by given n and has the same set of digits. Input : n = 1782 Output : m = 7128 Simp
6 min read
Count lexicographically smallest subsequences after rearrangement
Given a string S of length N, then your task is to find number of subsequences Y of string S such that: Y must be non-empty string and Y must be lexicographically smallest among all the possible strings obtained by rearranging the characters of Y.Examples: Input: N = 2, S = "ju"Output: 3Explanation: Three possible strings can be: {"j", "u", "ju"}.
6 min read
Maximum adjacent pair sum by array rearrangement
Given an array arr[] of size N, find the maximum value of adjacent sum by rearranging array in any order. Examples: Input: arr[] = {1, 2, 3, 4}Output: 17Explanation: The arrangement is {1, 3, 4, 2} where sum of all the adjacent element is (1 + 3) + (3 + 4) + (4 + 2) = 17 which is maximum. Input: arr[] = {5, 2, 3, 4, 6}Output: 35Explanation: The arr
5 min read
Array Rearrangement
Arrays are fundamental data structures in programming, allowing us to store and manipulate collections of related data. One common operation we may need to perform on arrays is rearranging their elements. Array rearrangement can serve various purposes, such as sorting the elements, reversing the order, or positioning specific elements in desired lo
3 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Find common elements in three sorted arrays by dictionary intersection
One way to efficiently find shared items in three sorted arrays is by using dictionary intersection. However, it's important to note that dictionaries are commonly used for unique keys, so if there are duplicate elements in your arrays, some adjustments may be needed to make this approach work. Given three arrays sorted in non-decreasing order, pri
4 min read
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | Set 2
Given two equal-size strings s[] and t[] of size N. In one step, choose any character of t[] and replace it with another character. Return the minimum number of steps to make t[] an anagram of s[]. Note: An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. Examples: Input: s = "baa", t = "aba
6 min read
Minimize deletion or append to make consecutive occurrence of all elements equal
Given an array arr[] of size N having positive elements, the task is to find the minimum number of deletion or append operations to make consecutive occurrences of all elements equal. Examples: Input: N = 4, arr[] = {1, 1, 2, 2}Output: 0Explanation: All the consecutive elements have the same value and same frequency already. Therefore, no operation
15 min read
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
Given two strings s1 and s2, we need to find the minimum number of manipulations required to make two strings anagram without deleting any character. Note:- The anagram strings have same set of characters, sequence of characters can be different. If deletion of character is allowed and cost is given, refer to Minimum Cost To Make Two Strings Identi
10 min read
Python | Minimum number of subsets with distinct elements using Counter
You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible. Examples: Input : arr[] = {1, 2, 3, 4} Output :1 Explanation : A single subset can contains all values and all values are distinct Input : arr[] = {1, 2, 3, 3} Output : 2 Explanatio
4 min read
Anagram checking in Python using collections.Counter()
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input : str1 = “abcd”, str2 = “dabc” Output : True Input : str1 = “abcf”, str
2 min read
Deletion in Hash Tables using Python
Hash tables are fundamental data structures used in computer science for efficient data storage and retrieval. They provide constant-time average-case complexity for basic operations like insertion, deletion, and search. Deletion in hash tables involves removing an element from the table based on its key. Python offers built-in support for hash tab
2 min read
Create a Counter App Using React, Tailwind and Django Framework
This article will guide you in creating a Counter using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Counter in Python using the Django Framework. What is Counter App?The Counter app is a straightforward tool designed for easy
6 min read
Python | Intersection of two String
One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings. There are various ways in Python, through which we can perform the Intersection of two strings. Method #1 : Naive Method Create an empty string and check for new occurrence of character common to both string a
3 min read
Create Word Counter app using Django
In this article, we are going to make a simple tool that counts a number of words in text using Django. Before diving into this topic you need to have some basic knowledge of Django. Refer to the below article to know about basics of Django. Django BasicsHow to Create a Basic Project using MVT in Django ? Now moving forward to make our wordcounter,
3 min read
Minimize deletions to reduce String to size 1 wherein ith deletion, N/2^i occurrences of (X+i-1)th character can be deleted
Given string str of length N and a character X, where N is always of the form 2k, the task is to find the minimum replacement operations required to reduce the size of the string to 1 wherein ith deletion, N/2i occurrences of (X + i - 1)th character can be deleted either from the front or the back of the string. Example: Input: str = "CDAAAABB", X
7 min read
Minimum steps to delete a string after repeated deletion of palindrome substrings
Given a string containing characters as integers only. We need to delete all characters of this string in a minimum number of steps wherein in one step we can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated. Examples: Input : s = “2553432” Output : 2 We can delete all character of above string
15+ min read
Deletion of character in String
Given a string str and an integer position pos, the task is to delete the character at the specified position pos from the string str. Examples: Input: str = "GeeksforGeeks", pos = 5Output: GeeksorGeeks Input: str = "HelloWorld", pos = 0Output: elloWorld Deletion of character in String using Loop:Traverse the string and push all the characters to a
4 min read
Python Counter to find the size of largest subset of anagram words
Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input: ant magenta magnate tan
5 min read
Python Counter| Find duplicate rows in a binary matrix
Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicate of rows which are already present in the matrix. Examples: Input : [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] Output : (1, 1, 0, 1, 0, 1) (0, 0, 1, 0, 0, 1) We have existi
2 min read
Python Counter | Majority Element
Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows: Examples: Input : 3 3 4 2 4 4 2 4 4 Output : 4 Input : 3 3 4 2 4 4 2 4 Out
2 min read
Python Counter.update() Method
Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In this article, we will understand about the Counte
2 min read