Check whether Two Strings are Anagrams of each other

Write a program to check whether two strings are anagrams of each other.

What is an Anagram ?

Two strings are said to be anagrams of each other if it contains the same characters, only the order of characters in both the strings is different. In other words, both strings must contain the same exact letters in the same exact frequency.

Let’s understand it through an example –

For example –

i)

str1 – car

str2 – rac

In this example, str1 and str2 are anagrams of each other. As both the strings contain the same letters only the order of characters in both the strings is different.

ii)

str1 – code

str2 – dock

In this example, str1 and str2 are not an anagram of each other. As both, the strings contain different letters.

Check whether two strings are anagrams of each other

Check whether two strings are anagrams of each other

Subscribe Our Tutorials

Get Latest Updates on Facebook

Now we know what’s an Anagram . Let’s think for a moment how do you write a code to check whether two strings are anagrams of each other.

You can solve this problem using multiple approaches. Let’s discuss some

Programming questions for practice

How to Check whether Two Strings are Anagrams of each other

Method  1 – Use Sorting

The easiest approach is to sort both the strings and after sorting compare them. If sorted strings is equal then it’s an anagram otherwise it’s not.

The time complexity of this approach is O(nlogn).

Java Code to Check whether Two Strings are Anagrams of each other using Sorting

 

PHP Code to Check whether Two Strings are Anagrams of each other using Sorting

How to sort a string in PHP

Programming questions on Linked List

METHOD 2- Check if both Strings have the same count for each character

In this method, we count each character of the first string then subtracting it from the count of the second string. Finally, check if the character count is zero. It it is not zero(0) then the two string is not an anagram.

The time complexity of this approach is O(n).

Check Whether Two Strings are Anagrams of each other – Java Code

PHP Code – Check whether Two Strings are Anagrams of each other

 

WebRewrite

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.