Java Program to Check If Two Strings are Anagram | Anagram Program

Less known facts about Java

Being one of the most durable programming languages, Java is used across the globe because of its robust and flexible features. The stability and versatility of Java have made it one of the most sought-after programming languages. However, there are several less known facts about this secure programming language. Let’s get to know a few of them.

  • Oak is the original name of Java.
  • You can earn a lot while learning this programming language.
  • Java is the second most populous programming language in the world, the first one being the C.
  • About 3 billion devices across the world are working on Java.
  • Java is a case sensitive programming language. i.e., “Final” and “final” are not the same in Java code. Read more on why java is so popular with the developers.

An Overview of Anagram

If a string is transformed into another string by rearranging its characters, then the two strings are said to be the anagrams of each other. However, the number of characters in the initial string and the string obtained should be the same. To understand the concept of an anagram in a better manner, let us consider two strings, ‘god’ and ‘dog’.

The strings ‘god’ and ‘dog’ are anagrams of each other because the former string can be rearranged to get the latter one just by interchanging the positions of characters ‘d’ and ‘g’. For any two input strings, the frequency of each character is calculated to check whether the strings are anagrams of each other or not. So, an anagram of a string can be defined as any other string that has the same characters with the same frequency as in the input string in any sequence.

Algorithm for Anagram Program in Java

Step 1: Define the two input strings.

Step 2: The length of each string is determined. Input strings are not anagrams of each other if they have different string lengths.

Step 3: If the strings have the same length, the string characters are converted to lower case letters to ensure the comparison easier.

Step 4: The string characters are either sorted by inbuilt functions or converted into a character array and then sorted. 

Step 5: The sorted array of characters are checked for equality. 

Implementation of Anagram program in Java

There are several solutions to implement a code to find whether two strings are anagrams or not. For each solution discussed in the subsequent sections, Step 2 of the algorithm described above forms the basis and facilitates early exit if the string lengths do not match. In the subsequent sections, let’s understand more about the different types of writing a code for anagram logic.

Sorting Approach

The characters of each input string can be sorted to obtain two normalized character arrays. If the normalized arrays of both the input strings are the same, then the strings are considered to be anagrams of each other and vice versa. 

The understanding and implementation of this code are easier. The time complexity of the above solution is O(n log n) and additional space is required to store character arrays of the input strings.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Counting Approach to Implementing Anagram Logic

In this approach, the number of existences of each character in the two input strings is measured. If the frequency of each character in both the strings is identical, the strings are anagrams of each other. 

Let us build a single histogram to save some memory. In the first string, the counts of each character are incremented, whereas the counts are decremented for the second one. If the ultimate result balances everything to zero, then the strings are anagrams.  

This solution executes faster than the previous solution and its time complexity is O(n). However, additional space is required to count the characters. This solution is practically effective only for strings with a smaller character range. Another fact about this solution is it uses a limited number of inbuilt Java functions and thus increases the length of the code. 

Checkout: Java Project Ideas & Topics

Determine Anagrams by checking with MultiSet

The use of MultiSet, a collection that aids order-independent comparison with identical elements, simplifies the process of counting and comparing in this solution. 

Each input string is initially converted into a MultiSet of characters and then checked for parity. 

The time complexity of this solution is O(n). It is similar to the counting approach to determine anagrams. However, it can work efficiently for strings of greater lengths. Also, coding involves a greater number of Java Library functions.

Letter Based Approach to determine Anagrams

All the solutions discussed so far consider the punctuation characters also as a part of the string. Moreover, those solutions are case sensitive. The letter-based approach implements a code to check the input strings based on the linguistic definition of anagrams. In this approach, the white spaces and punctuations are not considered as a part of the input string.

The initial step while implementing a letter-based solution is the elimination of unwanted characters and conversion of all valid characters into lowercase letters. After this step, any of the above-discussed implementations can be used to check whether the strings are anagrams or not. 

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Want to share this article?

Land on Your Dream Job

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks