Python Program to Check if Two Strings are Anagram - GeeksforGeeks (2024)

Last Updated : 06 Sep, 2024

Summarize

Comments

Improve

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
Python
# Python3 program for the above approachfrom collections import Counter# function to check if two strings are# anagram or notdef check(s1, s2): # implementing counter function if(Counter(s1) == Counter(s2)): print("The strings are anagrams.") else: print("The strings aren't anagrams.")# driver codes1 = "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

Python
## Example 1 for "The strings are anagrams."#Declare Inputsinp1 = "listen"inp2 = "silent"#Sort Elementsx = [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 checkedif (x == y):print("The strings are anagrams.")else: print("The strings aren't anagrams.")## Example 2 for "The strings aren't anagrams."#Declare Inputsinp1 = "listen"inp2 = "silenti"#Sort Elementsx = [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 checkedif (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.
Python
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 implementationdef 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.

Python
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] += 1for char in char_list_2: if char not in char_count: print("The strings are not anagrams.") break char_count[char] -= 1else: 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.



S

Striver

Python Program to Check if Two Strings are Anagram - GeeksforGeeks (1)

Improve

Previous Article

Python program to check if a string has at least one letter and one number

Next Article

Program to print right and left arrow patterns

Please Login to comment...

Python Program to Check if Two Strings are Anagram - GeeksforGeeks (2024)
Top Articles
Is $100 Enough for Forex? How Much Money to Start Forex Trading
How Long Does It Take To Learn Forex Trading?
The Blackening Showtimes Near Century Aurora And Xd
Woodward Avenue (M-1) - Automotive Heritage Trail - National Scenic Byway Foundation
Chris Provost Daughter Addie
Myhr North Memorial
How Far Is Chattanooga From Here
How Quickly Do I Lose My Bike Fitness?
No Strings Attached 123Movies
Betonnen afdekplaten (schoorsteenplaten) ter voorkoming van lekkage schoorsteen. - HeBlad
Busty Bruce Lee
Calmspirits Clapper
Jvid Rina Sauce
Guidewheel lands $9M Series A-1 for SaaS that boosts manufacturing and trims carbon emissions | TechCrunch
800-695-2780
Mail.zsthost Change Password
Does Breckie Hill Have An Only Fans – Repeat Replay
Dtab Customs
Violent Night Showtimes Near Amc Fashion Valley 18
Union Ironworkers Job Hotline
Rondom Ajax: ME grijpt in tijdens protest Ajax-fans bij hoofdbureau politie
Labby Memorial Funeral Homes Leesville Obituaries
Mccain Agportal
Leccion 4 Lesson Test
Marine Forecast Sandy Hook To Manasquan Inlet
Ivegore Machete Mutolation
Highmark Wholecare Otc Store
Mals Crazy Crab
The Boogeyman (Film, 2023) - MovieMeter.nl
Rek Funerals
Miles City Montana Craigslist
Mobile crane from the Netherlands, used mobile crane for sale from the Netherlands
N.J. Hogenkamp Sons Funeral Home | Saint Henry, Ohio
Tokioof
How to Use Craigslist (with Pictures) - wikiHow
Why Holly Gibney Is One of TV's Best Protagonists
Midsouthshooters Supply
Elisabeth Shue breaks silence about her top-secret 'Cobra Kai' appearance
Jack In The Box Menu 2022
R: Getting Help with R
Shell Gas Stations Prices
Noh Buddy
Makes A Successful Catch Maybe Crossword Clue
Scott Surratt Salary
Craigslist Pet Phoenix
Santa Ana Immigration Court Webex
Autozone Battery Hold Down
How To Connect To Rutgers Wifi
Convert Celsius to Kelvin
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 5875

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.