Check if Two Strings Are Anagrams (Java)
In this post, we will learn how to check whether two strings are anagrams of each other using Java. We will solve the problem using two different techniques and test it with multiple input strings.
What is an Anagram?
Two strings are called anagrams if they contain the same characters with the same frequencies, but possibly in a different order.
Examples:
listen & silent → Anagram letm & metl → Anagram hello & world → Not an Anagram
Approaches Used
- Naive Approach: Sort both strings and compare
- Efficient Approach: Frequency Count using array
Java Code Implementation
import java.util.Arrays;
public class AnagramCheck {
static final int CHAR = 256;
public static void main(String[] args) {
String[][] testCases = {
{"letm", "metl"},
{"listen", "silent"},
{"hello", "world"},
{"triangle", "integral"}
};
for (String[] pair : testCases) {
String s1 = pair[0];
String s2 = pair[1];
System.out.println("Strings: " + s1 + " , " + s2);
System.out.println("Naive Check: " + isAnagramNaive(s1, s2));
System.out.println("Efficient Check: " + isAnagramEfficient(s1, s2));
System.out.println();
}
}
// Naive approach using sorting
private static boolean isAnagramNaive(String s1, String s2) {
if (s1.length() != s2.length())
return false;
char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
return Arrays.equals(a1, a2);
}
// Efficient approach using frequency count
private static boolean isAnagramEfficient(String s1, String s2) {
if (s1.length() != s2.length())
return false;
int[] count = new int[CHAR];
for (int i = 0; i < s1.length(); i++) {
count[s1.charAt(i)]++;
count[s2.charAt(i)]--;
}
for (int i = 0; i < CHAR; i++) {
if (count[i] != 0)
return false;
}
return true;
}
}
Explanation
1. Naive Approach (Sorting Technique)
- Convert both strings to character arrays
- Sort both arrays
- If sorted arrays are equal, the strings are anagrams
Technique Used: Sorting
2. Efficient Approach (Frequency Count)
- Create a frequency array of size 256 (ASCII characters)
- Increment count for characters of first string
- Decrement count for characters of second string
- If all values are zero, strings are anagrams
Technique Used: Frequency Count / Hashing using Array
Sample Output
Strings: letm , metl Naive Check: true Efficient Check: true Strings: listen , silent Naive Check: true Efficient Check: true Strings: hello , world Naive Check: false Efficient Check: false
Time & Space Complexity
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Naive (Sorting) | O(n log n) | O(n) |
| Efficient (Frequency Count) | O(n) | O(1) |
Interview Tip
The frequency count approach is preferred in interviews because it runs in linear time and avoids sorting overhead.
Optimization Note
If the strings contain only lowercase alphabets (a to z),
a frequency array of size 26 can be used instead of 256.
Category: Strings
Difficulty: Easy
Technique: Sorting, Frequency Count
No comments:
Post a Comment