Open In App

Python Program to Check if Two Strings are Anagram

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Question:

Given two strings s1 and s2, check if both the strings are anagrams of each other.

Examples: 

Input : s1 = "listen"
        s2 = "silent"
Output : The strings are anagrams.


Input : s1 = "dad"
        s2 = "bad"
Output : The strings aren't anagrams.

Solution:

Method #1 : Using sorted() function

Python provides a inbuilt function sorted() which does not modify the original string, but returns sorted string.
Below is the Python implementation of the above approach: 

Python




# function to check if two strings are
# anagram or not
def check(s1, s2):
     
    # the sorted strings are checked
    if(sorted(s1)== sorted(s2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")        
         
# driver code 
s1 ="listen"
s2 ="silent"
check(s1, s2)


Output

The strings are anagrams.

Time Complexity: O(nlogn)

Auxiliary Space: O(1)

Method #2 : Using Counter() function

  • Count all the frequencies of 1st string and 2 and using counter()
  • If they are equal then print anagram

Python3




# Python3 program for the above approach
from collections import Counter
 
# function to check if two strings are
# anagram or not
def check(s1, s2):
   
    # implementing counter function
    if(Counter(s1) == Counter(s2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")
 
 
# driver code
s1 = "listen"
s2 = "silent"
check(s1, s2)


Output

The strings are anagrams.

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

Method #3: Using Inbuilt List and Sort() Methods

Taking 2 User Inputs and appending to a list and then sorting the elements in a list and it checks If they are equal then print anagram else aren’t anagrams

Python3




## Example 1 for "The strings are anagrams."
 
#Declare Inputs
inp1 = "listen"
inp2 = "silent"
 
#Sort Elements
x = [inp1[i] for i in range(0,len(inp1))]
x.sort()
y = [inp2[i] for i in range(0,len(inp2))]
y.sort()
 
# the sorted strings are checked
if (x == y):print("The strings are anagrams.")
else: print("The strings aren't anagrams.")
 
## Example 2 for "The strings aren't anagrams."
 
#Declare Inputs
inp1 = "listen"
inp2 = "silenti"
 
#Sort Elements
x = [inp1[i] for i in range(0,len(inp1))]
x.sort()
y = [inp2[i] for i in range(0,len(inp2))]
y.sort()
 
# the sorted strings are checked
if (x == y):print("The strings are anagrams.")
else: print("The strings aren't anagrams.")


Output

The strings are anagrams.
The strings aren't anagrams.

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Method #4: Using a dictionary to achieve constant time complexity

A dictionary in python provides constant time lookup. The algorithm is very simple and works like this:

  1. Loop through the characters of the two strings simultaneously. Suppose c1 is the current character of the first string and c2 the current character of the second string.
  2. For each of c1 and c2, say c, do the following:
    1.  If c is not present as a key in the dictionary, then create a dictionary entry with the key being c and the value being 
      • 1  if c is c1 (current character of the first string)
      • -1 if c is c2 (current character of the second string)
    2.  If c is present as a key in the dictionary, then instead of creating a new key-value pair, just increase or decrease the value in a similar way as in the previous step.
  3. After that, loop through the dictionary. If there is a key-value pair in the dictionary where it’s value is different than 0, the two strings and not anagram. Otherwise, they are.

Python3




def anagrams(inp1: str, inp2: str) -> bool:
  # if the length of the two strings is not the same, they are not anagrams.
  if len(inp1) != len(inp2):
      return False
 
  # initialize the dictionary
  counts = {}
 
  # loop simultaneously through the characters of the two strings.
  for c1, c2 in zip(inp1, inp2):
    if c1 in counts.keys():
      counts[c1] += 1
    else:
      counts[c1] = 1
    if c2 in counts.keys():
      counts[c2] -= 1
    else:
      counts[c2] = -1
 
  # Loop through the dictionary values.
  # if the dictionary contains even one value which is
  # different than 0, the strings are not anagrams.
  for count in counts.values():
    if count != 0:
      return False
  return True
 
# test the implementation
def main():
  inp1 = "listen"
  inp2 = "silent"
  if anagrams(inp1, inp2):
    print(f"{inp1} and {inp2} are anagrams")
  else:
    print(f"{inp1} and {inp2} are not anagrams")
 
if __name__ == "__main__":
  main()


Output

listen and silent are anagrams

Time Complexity: O(n) since we have to loop through all characters for both of the strings.
Auxiliary Space: O(n) in the worst case where all letters are different for even one of the string inputs. If both string inputs have eg. 4 letters out of which only 2 are different (eg. “SaaS” and “SaSa”), the space needed would be O(n/2)

Approach#5:using list and dictionary

Algorithm

1.Convert both strings to lists of characters.
2.Create a dictionary to count the frequency of each character in the first string.
3.Iterate over the characters of the second string and decrement the corresponding count in the dictionary.
4.If all counts in the dictionary are zero, the strings are anagrams.

Python3




s1 = "dad"
s2 = "bad"
 
char_list_1 = list(s1)
char_list_2 = list(s2)
 
char_count = {}
 
for char in char_list_1:
    if char not in char_count:
        char_count[char] = 0
    char_count[char] += 1
 
for char in char_list_2:
    if char not in char_count:
        print("The strings are not anagrams.")
        break
    char_count[char] -= 1
 
else:
    for count in char_count.values():
        if count != 0:
            print("The strings are not anagrams.")
            break
    else:
        print("The strings are anagrams.")


Output

The strings are not anagrams.

Time complexity: O(n), where n is the length of the longer string.

Space complexity: O(n), where n is the length of the longer string.

 



Next Article

Similar Reads

Python Program To Check Whether Two Strings Are Anagram Of Each Other
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 the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
8 min read
Java Program To Check Whether Two Strings Are Anagram
Write a function to check whether two given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. Program to Check Two Strings Are Anagram Of Each Other in JavaBelow is the Prog
8 min read
C++ Program To Check Whether Two Strings Are Anagram Of Each Other
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 the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
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 the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
Check whether two Strings are anagram of each other
Given two strings. The task is to check whether the given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. Examples: Input: str1 = "listen" str2 = "silent"Output: "Anagram"
15+ 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
Length of longest prefix anagram which are common in given two strings
Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str2 are "a", and "c".Prefixes of length 2 of string
8 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
Remove minimum number of characters so that two strings become 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"
13 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
Article Tags :
Practice Tags :
three90RightbarBannerImg