Write a program to check two strings are anagrams
👋 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!
using arrays.sortsort 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); } }using count arrayThis 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
countof 256 lengthIterate over the first string
str1In each iteration, we increment the count of the first String
str1and decrement the count of the second Stringstr2If 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;
}
}
using hashMapWe 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(); }