Check Anagram Strings in Java
Two strings are called Anagrams if they contain the same characters with the same frequency but in a different order.
Anagram checking is a popular interview question and is commonly used in string analysis, search engines, and text processing.
Rules for Anagram Strings
- Both strings must have the same length.
- Both strings must contain the same characters.
- Character frequency must be identical.
- Order of characters does not matter.
How the Logic Works
- If the lengths of both strings are different, they are not anagrams.
- Create an integer array to store character frequencies.
- Increment count for characters of the first string.
- Decrement count for characters of the second string.
- If all values are zero, the strings are anagrams.
Example 1
String 1: "listen"
String 2: "silent"
Result: Strings are Anagrams
Example 2
String 1: "hello"
String 2: "world"
Result: Strings are Not Anagrams
Java Program to Check Anagram Strings
import java.util.Scanner;
public class AnagramCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = sc.nextLine();
System.out.print("Enter second string: ");
String str2 = sc.nextLine();
// Remove spaces and convert to lowercase
str1 = str1.replace(" ", "").toLowerCase();
str2 = str2.replace(" ", "").toLowerCase();
if (str1.length() != str2.length()) {
System.out.println("Strings are Not Anagrams");
return;
}
int[] freq = new int[256];
for (int i = 0; i < str1.length(); i++) {
freq[str1.charAt(i)]++;
freq[str2.charAt(i)]--;
}
boolean isAnagram = true;
for (int count : freq) {
if (count != 0) {
isAnagram = false;
break;
}
}
if (isAnagram) {
System.out.println("Strings are Anagrams");
} else {
System.out.println("Strings are Not Anagrams");
}
}
}
Sample Output
Enter first string: listen
Enter second string: silent
Strings are Anagrams
Enter first string: java
Enter second string: avaJ
Strings are Anagrams
Important Notes
- Spaces are ignored in this program.
- Comparison is case-insensitive.
- Time complexity is O(n).
Practice Challenges
- Check anagrams without using an array.
- Check anagrams using sorting logic.
- Check anagrams for Unicode characters.
Anagram checking improves your understanding of character frequency and efficient string comparison techniques.