Checking if 2 given strings are anagrams or not is one of the most common and easiest interview questions which is often asked in interview coding rounds. In this post we discuss method to identify if 2 strings are anagrams or not.
2 strings or words or phrases are said to be Anagrams if they are formed by rearrangement of same letters.
For example we consider "HOST" and "SHOT" they are formed by rearrangement of letters H,O,S,T.
We can find a lot of such examples.
Let us now discuss the method to check if 2 strings are anagrams.
Below is the implementation code in cpp, java, python.
If you don't want to use them then you can use the below code to do the same
Removing white spaces
Converting to lowercase
You might also be interested in
Double Linked List
Finding Middle node in a Linked List
Infix to Prefix Conversion
Infix to Postfix Conversion
Binary Search Tree
4 Different methods to swap values
2 strings or words or phrases are said to be Anagrams if they are formed by rearrangement of same letters.
For example we consider "HOST" and "SHOT" they are formed by rearrangement of letters H,O,S,T.
We can find a lot of such examples.
Let us now discuss the method to check if 2 strings are anagrams.
- First we remove all the white spaces from the given strings.
- For strings to be anagrams the length of the strings after removing white spaces must be same, so we compare lengths.
- if the lengths are equal then we move forward.
- else we stop as the length of the strings must be same.
- The next step is to convert the string to lowercase, this step is optional and you can choose not to do it depending on your requirement.
- Then we need to sort all the characters of the string.
- Finally we compare the sorted string
- if the strings are equal then they are anagrams.
- else they are not anagrams.
Below is the implementation code in cpp, java, python.
C++ Program
For the c++ program I have used standard methods from algorithms and cctype to remove whitespaces and convert string to lower case,If you don't want to use them then you can use the below code to do the same
Removing white spaces
Converting to lowercase
Sample input and output to check the program
Double Linked List
Finding Middle node in a Linked List
Infix to Prefix Conversion
Infix to Postfix Conversion
Binary Search Tree
4 Different methods to swap values
Comments
Post a Comment