Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Java Arrays
1.2.
Java Strings
1.3.
Anagrams
2.
Solution Approach 1(Using Sorting)
2.1.
Algorithm:
2.2.
Program:
2.2.1.
Output:
3.
Solution Approach 2(Using Hashmap)
3.1.
Algorithm:
3.2.
Program:
3.2.1.
Output:
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Check if Two Strings are Anagrams

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

In this tutorial, we'll use Java to see if two strings are anagrams or not. Before moving on to the program for checking whether two strings are anagram, we will go through the basics of Java Strings and Java Arrays.

Let’s get started, I hope you learn a lot from this article.

Java Arrays

We can define an array as a collection of data of similar types. Furthermore, an array's items are kept in a single memory address. It's a data structure where we save similar items. We can only store a fixed number of elements in a Java array. You must decide on the array's size before you begin. You can't change the size of an array once you create an array.

Each memory location in the Java array is assigned a number. We use the term ‘array index’ for this number. We can also use this index number to initialise arrays in Java. The compiler assigns the 0th index to the array's first element, the 1st index to the array's second member, etc. We can create single-dimensional and multidimensional arrays in Java, just like in C/C++.

Example of array declaration in Java:

int array[]=new int[10];

Java Strings

In Java, a string is a collection of char values represented as an object. An array of characters functions similarly to a Java string. Java Strings are a great way to store data in your application. We can use them to store anything from simple text to complex objects. Java String is immutable, which means once we create a string, we can not change it. This property makes them ideal for storing information that needs to remain constant throughout the program's life.

The String class in Java has numerous methods for manipulating strings: concat(), equals(), split(), replace(), substring(), intern(), etc.

Anagrams

An anagram of a string is a distinct string made up of the same characters in a different order. "arc" and "car" are anagrams of each other.

(Image showing different words that are anagrams to each other)

Also Read About, Multithreading in java, and Duck Number in Java.

Solution Approach 1(Using Sorting)

In the first method to check whether two strings are anagram are not, we will use sorting. We have to sort both the strings and compare both sorted strings. If they are found to be equal, the strings are anagram; otherwise, not.

Algorithm:

  1. START
  2. Take USER INPUT first_string and second_string.
  3. CONVERT first_string, second_string to lowercase
  4. PRINT "Not Anagram" if the lengths of first_string and second_string are not equal; otherwise, proceed to Step 5.
  5. CONVERT first_string, second_string to character arrays
  6. SORT the arrays
  7. COMPARE the arrays and print "Strings are Anagram" if they are equal; else, print "Strings are not Anagram."
  8. END

Program:

/*Program to check if two strings are anagram*/
import java.util.*;
class CheckAnagram
{
    public static void main(String args[])
    {
        //taking input from user
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the first string");
        String s1=sc.nextLine();
        System.out.println("Enter the second string");
        String s2=sc.nextLine();
        //converting string to lower case
        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();
        //converting string to character array
        char[] ch1=s1.toCharArray();
        char[] ch2=s2.toCharArray();
        //sorting the character array
        Arrays.sort(ch1);
        Arrays.sort(ch2);
        //display if strings are anagram or not
        if(Arrays.equals(ch1,ch2))
        {
            System.out.println("The strings are anagram");
        }
        else
        {
            System.out.println("The strings are not anagram");
        }
    }
}

Output:

We took the user’s inputs in the Java program above. Then we converted the input strings to lower case. Again, we converted strings to character arrays. Now we sort the array and check if both sorted arrays are equal. If both the sorted arrays are equal, we display the message “The strings are anagram” otherwise display “The strings are not an anagram.”

Time Complexity: O(N log N)

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Solution Approach 2(Using Hashmap)

We learnt to check if two strings are anagrams using sorting in the above program. Now, we will learn to code the same using the Hashmap method in Java. Let’s get started with the hashmap method to check whether both the strings are anagrams or not.

Algorithm:

  1. START
  2. Take User INPUT first_string and second_string.
  3. CONVERT first_string, second_string to lowercase
  4. INITIALISE count variable to 0.
  5. CREATE a HashMap object with the key character and the value of character occurrences.
  6. If the character appears in the first string, the character count is INCREASED by one.
  7. If the character appears in the second string, the character count is DECREASED by one.
  8. ITERATE through HashMap, checking the count of each character on the map.
  9. DISPLAY “Strings are anagram” if the count is 0, otherwise “Strings are not an anagram.”
  10. END

Program:

/*Program to check two strings anagram using hashmap*/
import java.util.*;
class CheckAnagram
{
    public static void main(String args[])
    {
        //taking input from user
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the first string");
        String s1=sc.nextLine();
        System.out.println("Enter the second string");
        String s2=sc.nextLine();
        //converting string to lower case
        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();
        //initialising count to 0
        int count=0;
        //creating hashmap
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        for(int i=0;i<s1.length();i++)
        {
            if(hm.containsKey(s1.charAt(i)))
            {
                hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
            }
            else
            {
                hm.put(s1.charAt(i),1);
            }
        }
        for(int i=0;i<s2.length();i++)
        {
            if(hm.containsKey(s2.charAt(i)))
            {
                hm.put(s2.charAt(i),hm.get(s2.charAt(i))-1);
            }
            else
            {
                hm.put(s2.charAt(i),-1);
            }
        }
        for(Map.Entry<Character,Integer> m:hm.entrySet())
        {
            if(m.getValue()!=0)
            {
                count++;
            }
        }
        //print the result
        if(count==0)
        {
            System.out.println("The two strings are anagram");
        }
        else
        {
            System.out.println("The two strings are not anagram");
        }
    }
}

Output:

In the hashmap method, we have incremented the value of the key for the first array, decrement the value for the second array, and then validated the map size. We have taken two strings as input from the user and checked if they are anagrams or not.

Time-Complexity: O(N)

Try it by yourself on java online compiler.

Also check out Addition of Two Numbers in Java here.

Must Read Array of Objects in Java

FAQs

  1. In Java, how do you create an array?
    To begin, create a variable with the array type you want. Second, allocate memory for the array with new and assign it to the array variable. As a result, dynamic allocation occurs in the case of Java arrays.
    Syntax:
    → type variable-name[];
    → type[] variable-name;
     
  2. In Java, why is it that strings are immutable?
    Because of security, synchronisation and concurrency, caching, and class loading, the String in Java is immutable. The purpose of declaring string final is to break its immutability and prevent others from extending it. The String pool caches the String objects, which makes the String immutable.
  3. What data type is string Java?
    A String in Java is a non-primitive data type. We can use methods on the String object to execute various string operations.
  4. What are the characteristics of the Java programming language?
    The Java Programming Language has the following features:
    → Portability
    → Object-Oriented programming language
    → Platform independent
    → Robustness
    → Dynamic
    → Distributed
    → Multithreaded

Key Takeaways

In this post, we learned:

  • the basics of Java Strings
  • Java Arrays and what an anagram is.
  • To create a Java program to check if two strings are anagram or not. 
  • We took two input strings from the user and stored them in two different strings. 
  • We converted them to lower cases and sorted them. If they are equal, both strings are anagram; otherwise, they are not.

We hope you've better understood basic java programming and the program to check if two given strings are anagrams. If you're interested in finding out more, see our articles on ‘print characters in a string’ and ‘selenium interview questions.’ Please upvote our blog so that other ninjas can benefit from it.

Also check out - String Interview Questions In Java

Recommended problems -

 

Visit our practice platform Coding Ninjas Studio to get started. Here you can practice top problems, attempt mock tests, read interview experiences, and more.!

Happy Reading!

Previous article
Int to String Conversion in Java
Next article
Number of Characters in a String
Live masterclass