Skip to main content

Command Palette

Search for a command to run...

Write a program to check two strings are anagrams

Updated
3 min read
S

👋 Hey there! I’m Shohanur Rahman!

I’m a backend developer with over 5.5 years of experience in building scalable and efficient web applications. My work focuses on Java, Spring Boot, and microservices architecture, where I love designing robust API solutions and creating secure middleware for complex integrations.

💼 What I Do Backend Development: Expert in Spring Boot, Spring Cloud, and Spring WebFlux, I create high-performance microservices that drive seamless user experiences. Cloud & DevOps: AWS enthusiast, skilled in using EC2, S3, RDS, and Docker to design scalable and reliable cloud infrastructures. Digital Security: Passionate about securing applications with OAuth2, Keycloak, and digital signatures for data integrity and privacy. 🚀 Current Projects I’m currently working on API integrations with Spring Cloud Gateway and designing an e-invoicing middleware. My projects often involve asynchronous processing, digital signature implementations, and ensuring high standards of security.

📝 Why I Write I enjoy sharing what I’ve learned through blog posts, covering everything from backend design to API security and cloud best practices. Check out my posts if you’re into backend dev, cloud tech, or digital security!

  1. using arrays.sort

    sort both strings and compare the sorted strings

    Time Complexity: O(nLogn)

    Auxiliary space: O(1).

     import java.util.*;
    
     public class Main {
         public static void main(String[] args) {
             System.out.println(isAnagram("Race", "Care"));
         }
    
         public static boolean isAnagram(String str1, String str2) {
             // length check 
             if (str1.length() != str2.length()) return false;
    
             // convert strings to char array
             char[] charArray1 = str1.toLowerCase().toCharArray();
             char[] charArray2 = str2.toLowerCase().toCharArray();
    
             // sort the char array
             Arrays.sort(charArray1);
             Arrays.sort(charArray2);
    
             // if sorted char arrays are same
             // then the string is anagram
             return Arrays.equals(charArray1, charArray2);
         }
     }
    
  2. using count array

    This method assumes that the set of possible characters in both strings is small. In the following implementation, it is assumed that the characters are stored using 8 bits and there can be 256 possible characters.

    • Create an array named count of 256 length

    • Iterate over the first string str1

    • In each iteration, we increment the count of the first String str1 and decrement the count of the second String str2

    • If the count of any character is not 0 at the end, it means two Strings are not anagrams

      Time Complexity: O(n)

      Auxiliary space: O(n)

public class Main {
    public static void main(String[] args) {
        System.out.println(isAnagram("Race", "Care"));
    }

    public static boolean isAnagram(String str1, String str2) {
        // length check 
        if (str1.length() != str2.length()) return false;

        int[] count = new int[256];
        for (int i = 0; i < str1.length(); i++) {
            count[str1.charAt(i)]++;
            count[str2.charAt(i)]--;
        }
        for (int i = 0; i < 256; i++) {
            if (count[i] != 0) {
                return false;
            }
        }
        return true;
    }
}
  1. using hashMap

    We can optimize the space complexity of the above method by using HashMap instead of initializing 256 characters array. So in this approach, we will first count the occurrences of each unique character with the help of HashMap for the first string. Then we will reduce the count of each character when we encounter them in the second string. Finally, if the count of each character in the hash map is 0 then it means both strings are anagrams else not

     public class Main {
         public static void main(String[] args) {
             System.out.println(isAnagram("Race", "Care"));
         }
    
         public static boolean isAnagram(String str1, String str2) {
             // Check if both string has same length or not
                  if (str1.length() != str2.length()) {
                 return false;
             }
    
             str1 = str1.toLowerCase();
             str2 = str2.toLowerCase();
    
             Map<Character, Integer> map = new HashMap<>();
    
             for (int i = 0; i < str1.length(); i++) {
                 char ch = str1.charAt(i);
                 if (map.containsKey(ch)) {
                     map.put(ch, map.get(ch) + 1);
                 } else {
                     map.put(ch, 1);
                 }
             }
    
             for (int i = 0; i < str2.length(); i++) {
                 char ch = str2.charAt(i);
                 if (!map.containsKey(ch)) {
                     return false;
                 } else if (map.get(ch) == 1) {
                     map.remove(ch);
                 } else {
                     map.put(ch, map.get(ch) - 1);
                 }
             }
    
             // Return true if the HashMap is empty
             return map.isEmpty();
     }
    

More from this blog

Shohanur Rahman's blog

69 posts