Check whether Two Strings are Anagram of each other

Given two strings, we have to write a code to check whether two strings are anagram of each other or not. In this programming question, we are going to write a java code to check whether two strings are anagram of each other 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 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.

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 user. In this tutorial, i am going to discuss two approaches to solve this problem and also the end of this tutorial, i have mentioned a video link.

Programming Tutorials Video

Subscribe Our Tutorials

Get Latest Updates on Facebook

Java program to check anagram

Check whether Two Strings are Anagram

How to Check whether 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 is 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 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, we 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 if Two Strings are Anagram in Java

I have already explained a logic, let’s write a java code to check anagram.

About WebRewrite

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