Program to check two Strings are Anagram or not using Hashmap in Java

Today we are going to write a program to find or check whether two strings are an anagram or not using hashmap in Java. First, we should know what are anagrams. Anagrams are those words in which all the alphabets remain the same but their order is not. For eg.

hello   kite                 lata       cap
ellho   tike                 tapa       pat
These are anagrams           These are not anagram

Now in hashing we mark all the unique alphabets and keep a count that how many are these in a given string. Then we put this data into a hashmap in the form of (key, value) pair. Here the alphabet will be key and value will be its occurrences in the string For eg.  hashmap of “Apple” would look like this –

alphabet –  number of occurrences
a                   1
p                   2
l                    1
e                   1
You may also take a look at this: How to check whether two strings are anagram or not in Java?


Check two Strings are Anagram or not using Hashmap in Java

Now for two string to be anagram their hashmap will look the same. hence we can compare them and can tell if the strings are anagram or not.

import java.util.HashMap;
import java.util.Scanner;

public class ANAGRAM_STRING {

  public static void main(String[] args) {
    Scanner sc=new Scanner (;
     Boolean result=anagram(st1,st2);
    	 System.out.println("congrat! these are anagrams");
    	 System.out.println("these are not anagrams");

  static boolean anagram(String st1, String st2)
    HashMap<Character ,Integer> map1= new HashMap<Character ,Integer>();
    HashMap<Character ,Integer> map2= new HashMap<Character ,Integer>();
    int len1=st1.length();
    int len2=st2.length();
    char[] arr1=st1.toCharArray();
    char[] arr2=st2.toCharArray();
      return false;
    else {
    for(int i=0;i<len1;i++) {
        map1.put(arr1[i], 1);
      else {
     int count1= (int)map1.get(arr1[i]);
     map1.put(arr1[i], ++count1);
    for(int j=0;j<len2;j++) {
        map2.put(arr2[j], 1);
      else {
      int count2=(int)map2.get(arr2[j]);
      map2.put(arr2[j], ++count2);
      return true;
      return false;


these are not anagrams
congrat! these are anagrams

The complexity of this solution is O(n), which is much better than the naive solution. The naive solution for this problem will be to solve it with the help of two for loops where we compare each alphabet of string 1 with each one of string 2. The complexity of this solution will be O(n²).

Leave a Reply

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