Python Program to Check Whether Two Strings are Anagram to Each Other or Not29 Aug 2024 | 8 min read An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase. For example, the word "listen" is an anagram of "silent", and "fired" is an anagram of "fried" and vice versa. You are given two strings, and the problem is finding whether both strings are anagrams to each other or not. Example 1:Example 2:Method 1 - Using sorting to check whether the given strings are anagrams or notThe program can be summarized as follows:
Output: The two strings are anagrams. Explanation: The isAnangram function first checks whether string lengths are the same or not. The function returns false if the lengths are different, stating that the strings cannot be anagrams of each other. If the lengths are the same, the function sorts and compares the characters in each string. The function returns True if the sorted strings are the same, indicating that the original strings are anagrams. If the sorted strings are not the same, the original strings are not anagrams, and the function returns False. Time Complexity - O(n*logn): The sorting operation has the time complexity = O(n*logn). Space Complexity - O(n): Extra space is needed to store the sorted strings. Method 2 - Using an array to store the count of each character.The program can be summarized as follows:
Output: The two strings are anagrams. Explanation: The isAnangram function first checks whether string lengths are the same or not. The function returns false if the lengths are different, stating that the strings cannot be anagrams of each other. The function then initializes a frequency array freq of size 26 (for the 26 English alphabets) to count the frequency of each character in the first string str1. The frequency of each character is stored in the corresponding index of the freq array, using the ASCII values of the characters. The function then iterates over the characters in the second string str2 and decrements the frequency of each character in the freq array. If the frequency of a character in str2 is greater than the frequency in str1, then the strings cannot be anagrams, and the function returns False. The function returns True if the frequency of characters in str1 and str2 are the same. Time Complexity - O(n): The program iterates over each character of both strings, which makes its time complexity equal to O(n). Space Complexity - O(1): No extra space is needed. The size of the array is fixed for all 26 alphabets. Method 3 - Use a dictionary to count the frequency of characters.The program can be summarized as follows:
Output: The two strings are anagrams. Explanation: The isAnagram() function first creates an empty dictionary to store the frequency of each character in string 1. It then iterates over each character of string one using for loop, makes the character a key if it is not present, and then increments the frequency by one each time for that character. It then iterates over each character of string two using for loop and checks if the key is present in the dictionary or not or if the frequency of the character is zero or not. If any of the conditions are satisfied, it returns false. It decrements the frequency of each character one by one and returns True at the end of the program, indicating that both the strings are anagrams. Time Complexity - O(n): The program uses for-loop to iterate over both strings Space Complexity - O(n): It uses a dictionary to store the frequency. The size of the dictionary depends on the length of the string. Method 4 - Using Counter() from collectionsThe program can be summarized as follows:
Output: The two strings are anagrams. Explanation: The Counter class returns a dictionary object with each character as a key with frequency count as a value. The isAnagram() function checks whether the given strings are of the same length or not, as usual. If the strings are of different lengths, it returns False. Else, it creates two Counter objects, one for string one and another for string two. It compares both counters and returns the result. Time Complexity - O(n): Creating a counter depends on the size of the input, which makes the time complexity of the program equal to O(n). Space Complexity - O(n): The program creates two counters whose sizes depend on the input strings' length. Method 4 - Using the XOR operatorThe program can be summarized as follows:
Output: The two strings are anagrams. Explanation: The XOR operator gives 1 when two bits are different and 0 when two bits are same. The truth table of the XOR operator:
For example, if we XOR 10101 and 11011, we get: 10101 In Python, the XOR operator is represented using the caret (^) symbol. Let's take an example to understand the idea of the program. 5^3 = 6 Here, we first performed the bitwise XOR on 5 and 3. Then on 3 and 6 (the result of the previous operation). And at last, on 5 and 5 (the result of the previous operation). The same idea works for the above program. In the above program, we first concatenated both strings using the + operator str1 + str2. Using the for loop, we have iterated over each string and performed bitwise XOR with the result. The idea is that if both strings are anagrams, the result will be 0. Else, some integer. At the end of the program, we printed the result based on the value returned by the isAnagram function. Time Complexity - O(n): Where n represents the size of str1+str2. A for loop is used to iterate over the concatenated string. Space Complexity - O(1): No extra space is needed. Next TopicInput a list in Python |
? Introduction: This post will teach us how to employ Python to clean the Recycle Bin. The Recycle Bin is a temporary storage location for deleted files and folders on Windows systems. A deleted document or folder is relocated to the Recycle Bin in which it can if...
4 min read
In Data Science and Machine Learning, we frequently go over a term called Imbalanced Data Distribution, by and large, which happens when perceptions in one of the classes are a lot higher or lower than in different classes. Machine Learning calculations often increment exactness by diminishing...
11 min read
Reinforcement learning is a model in the Learning Process in which a learning agent develops, over time and in the best way possible within a particular environment, by engaging continuously with the surroundings. During the journey of learning, the agent will encounter different scenarios in the...
4 min read
Stacks are linear data structures that follow the Last-In-First-Out (LIFO) principle, which states that the item that was most recently added is the one that gets deleted first. A stack's fundamental commands are "push", "pop", "peek" (or top), and "isEmpty". Each stack element in a linked...
5 min read
When we write letters, emails, etc., we all commit spelling errors, or what we call typos. Even while writing this piece, many errors were made. To aid that, in these situations, we rely on the assistants or some applications. Do you know that using Python, you...
9 min read
In this tutorial, we will learn how to declare a global Variable in Python Program. What is a Global Variable? The global variables are the ones that are available both within and outside of any function, provided they are defined outside a function which is a global...
5 min read
In Python, a `container` is an object that holds other objects. Containers provide a way to organize and manage collections of data. Python provides several built-in container types, including `lists`, `tuples`, `sets`, and `dictionaries`. Each type has its own characteristics and use cases. Lists Lists are ordered collections...
2 min read
It seems to be a bit difficult to create your own Python module, but what if we say that creating or writing a Python program is a very simple task. In this tutorial, we are going to write a Python module, and after writing it, we...
4 min read
Matplotlib is a Python library that lets you make deterministic, animated, and engaging visualizations. It is used to make plots in Python, such as bar charts, scatter plots, pie charts, histograms, line plots, 3-D plots, and many more. The matplotlib library contains the information about the scatter...
6 min read
Create a Virtual Environment: In this tutorial, you will fabricate your undertaking structure. You can name the root envelope of your venture a way you like. For instance, you could name it rp_flask_api/. Make the organizer and explore into it: Syntax to Create a Folder in the Shell: $...
18 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India