Check whether Two Strings are Anagram of each other

Given two strings, write a code to check whether two strings are anagram of each other or not. In this tutorial, I am going to discuss multiple approaches and their java implementation to check if two strings are anagrams or not.

Let’s first understand what is an anagram? and how we are going to solve this problem.

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 this 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.

Now we know what’s an Anagram. Let’s think for a moment how do we solve this problem. What’s the approach we are going to use.

check whether two strings are anagrams of each other

Programming Video Tutorials

How to Check If Two Strings are Anagram of each other

Method  1 – Use Sorting

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

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

Sorting algorithms and their time complexity

Java Program to Check Anagram using Sorting

Programming questions on Linked List

METHOD 2- Check if Character Count is Same in Both the Strings

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

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

Check whether two strings are anagram of each other video tutorial

Check whether Two Strings are Anagram of each other in Java

In this code example, we are going to implement method 2. In which we check if character count is the same in both the strings.

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.