Open In App

Anagram checking in Python using collections.Counter()

Improve
Improve
Like Article
Like
Save
Share
Report

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”, str2 = “kabc”
Output : False

This problem has existing solution please refer Check whether two strings are anagram of each other link. We will solve this problem in python in a single line using collections.Counter() module

Implementation:

Python





Output

True

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

How dictionary comparison works in python ? 
If we have two dictionary data structures in python dict1 = {‘a’:2,’b’:3,’c’:1} and dict2 = {‘b’:3,’c’:1,’a’:2} and we compare both of them like dict1=dict2 then it will result True. In python ordinary dictionary data structure does not follow any ordering of keys, when we compare two dictionaries then it compares three checks in order number of keys (if they don’t match, the dicts are not equal), names of keys (if they don’t match, they’re not equal) and value of each key (they have to be ‘==’, too)


Last Updated : 21 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads