Open In App

Check if Two Strings are Anagram - Python

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of checking if two strings are anagrams in Python involves determining whether the two strings contain the same characters with the same frequency, but possibly in a different order. For example, given the strings "listen" and "silent", they are anagrams because both contain the same characters with identical frequencies, resulting in the output "Yes".

Using Hashmap

This is the most efficient and preferred method to check for anagrams. It uses a hashmap (dictionary) to count the frequency of each character in both strings and compares the two frequency maps. If both strings have identical character frequencies, they are anagrams.

Python
from collections import Counter  # for character frequency counting

s1 = "listen"
s2 = "silent"

if len(s1) != len(s2):  # check length
    print("No")
else:
    if Counter(s1) == Counter(s2):  # compare character counts
        print("Yes")
    else:
        print("No")

Output
Yes

Explanation: If the lengths are equal, Counter(s1) and Counter(s2) create frequency dictionaries for both strings. If they match, it prints "Yes" otherwise, it prints "No".

Using array

We know that the strings contain only lowercase English letters (a-z), we can use an array of size 26 to track the frequency of each character instead of using a hashmap. Each character is mapped to an index between 0 and 25 using the ord() function.

Python
s1 = "listen"
s2 = "silent"

if len(s1) != len(s2):  # check length
    print("No")
else:
    count = [0] * 26  # array to track character frequencies (a-z)

    for i in range(len(s1)):
        count[ord(s1[i]) - ord('a')] += 1  # increment for s1
        count[ord(s2[i]) - ord('a')] -= 1  # decrement for s2

    if all(x == 0 for x in count):  # check if all frequencies are zero
        print("Yes")
    else:
        print("No")

Output
Yes

Explanation: If the lengths are the same, an array count of size 26 is initialized to track letter frequencies. A loop increments indices for characters in s1 and decrements for s2. If all values in count are zero after the loop, it prints "Yes" otherwise, "No."

Using sorted()

This is the most efficient and simple method to check for anagrams. The idea is to sort both strings and compare the sorted versions. If both sorted strings are equal, they are anagrams.

Python
s1 = "listen"
s2 = "silent"

if sorted(s1) == sorted(s2):
    print("Yes")
else:
    print("No")

Output
Yes

Explanation: If the sorted versions of both strings are equal, it prints "Yes," indicating they are anagrams otherwise, it prints "No."


Next Article

Similar Reads