Solution: Two strings are anagrams if they have the same characters but in different order. For example, Angel and Angle are anagrams
There are a few ways to check if Strings are anagrams. Some of them are:
- Using String methods
- Using array.sort
- Using count array
- Using Java 8
Solution_1 : Using String methods
Algorithm:- Pass two Strings
word and anagram to method called isAnagramUsingStringMethods() - Iterate over first String
word and get char c from it using charAt() method - If index of char c is
-1 in second String anagram, then two strings are not anagrams - If index of char c is not equal to -1 in second String
anagram, then remove the character from the String anagram. - If you get empty String in the end, then two Strings are anagrams of each other.
package org.cloudTechtwitter;
public class StringAnagramMain {
public static void main(String[] args) {
String word = "cloudTechtwitter";
String anagram = "TechtwitterCloud";
System.out.println("cloudTechtwitter and TechtwitterCloud are anagrams :" + isAnagramUsingStringMethods(word, anagram));
}
public static boolean isAnagramUsingStringMethods(String word, String anagram) {
if (word.length() != anagram.length())
return false;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
int index = anagram.indexOf(c);
// If index of any character is -1, then two strings are not anagrams
// If index of character is not equal to -1, then remove the chacter from the
// String
if (index != -1) {
anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
} else
return false;
}
return anagram.isEmpty();
}
}
When you run above program, you will get below output:CloudTechtwitter and TechtwitterCloud are anagrams :true
Algorithm:
- Pass two Strings
wordandanagramto method calledisAnagramUsingStringMethods() - Iterate over first String
wordand get charcfrom it usingcharAt()method - If index of char c is
-1in second Stringanagram, then two strings are not anagrams - If index of char c is not equal to -1 in second String
anagram, then remove the character from the Stringanagram. - If you get empty String in the end, then two Strings are anagrams of each other.
package org.cloudTechtwitter; public class StringAnagramMain { public static void main(String[] args) { String word = "cloudTechtwitter"; String anagram = "TechtwitterCloud"; System.out.println("cloudTechtwitter and TechtwitterCloud are anagrams :" + isAnagramUsingStringMethods(word, anagram)); } public static boolean isAnagramUsingStringMethods(String word, String anagram) { if (word.length() != anagram.length()) return false; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); int index = anagram.indexOf(c); // If index of any character is -1, then two strings are not anagrams // If index of character is not equal to -1, then remove the chacter from the // String if (index != -1) { anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length()); } else return false; } return anagram.isEmpty(); } }
When you run above program, you will get below output:
CloudTechtwitter and TechtwitterCloud are anagrams :true
Solution_2 : Using Arrays.sort()
You can simply sort both the Strings using Arrays.sort() method. If both the Strings are equal after Sorting, then these two Strings are anagram of each other.:
package org.TechtwitterCloud;
import java.util.Arrays;
public class AnagramUsingSort {
public static void main(String[] args) {
String word = "CloudTechtwitter";
String anagram = "TechtwitterCloud";
System.out.println("TechtwitterCloud and CloudTechtwitter are anagrams :" + isAnagramUsingArraySort(word, anagram));
}
public static boolean isAnagramUsingArraySort(String word, String anagram) {
String sortedWord = sortChars(word);
String sortedAnagram = sortChars(anagram);
return sortedWord.equals(sortedAnagram);
}
public static String sortChars(String word) {
char[] wordArr = word.toLowerCase().toCharArray();
Arrays.sort(wordArr);
return String.valueOf(wordArr);
}
}
When you run above program, you will get below output:
TechtwitterCloud and CloudTechtwitter are anagrams :true
You can simply sort both the Strings using Arrays.sort() method. If both the Strings are equal after Sorting, then these two Strings are anagram of each other.:
package org.TechtwitterCloud; import java.util.Arrays; public class AnagramUsingSort { public static void main(String[] args) { String word = "CloudTechtwitter"; String anagram = "TechtwitterCloud"; System.out.println("TechtwitterCloud and CloudTechtwitter are anagrams :" + isAnagramUsingArraySort(word, anagram)); } public static boolean isAnagramUsingArraySort(String word, String anagram) { String sortedWord = sortChars(word); String sortedAnagram = sortChars(anagram); return sortedWord.equals(sortedAnagram); } public static String sortChars(String word) { char[] wordArr = word.toLowerCase().toCharArray(); Arrays.sort(wordArr); return String.valueOf(wordArr); } }
When you run above program, you will get below output:
TechtwitterCloud and CloudTechtwitter are anagrams :true
Solution_3 : Using Java 8
public static Boolean isAnagram(String word1, String word2){ List<String> listWord1 = new ArrayList<>(Arrays.asList(word1.split(""))); List<String> listWord2 = new ArrayList<>(Arrays.asList(word2.split(""))); Collections.sort(listWord1); Collections.sort(listWord2); word1 = String.join("", listWord1); word2 = String.join("", listWord2); return word1.equals(word2); }
Solution_4 : Using count array
Here is another approach to find if two Strings are anagrams.
- Pass two Strings str1 and str2 to method
isAnagram() - If length of str1 and str2 are not same, then they are not anagrams
- Create an array named
countof 256 length - Iterate over first string
str1 - In each iteration, we increment count of first String
str1and decrement the count of second Stringstr2 - If count of any character is not 0 at the end, it means two Strings are not anagrams
This approach has time complexity of O(n), but it requires extra space for count Array.
package org.TechtwitterCloud;
public class AnagramCountingMain {
public static void main(String args[])
{
boolean isAnagram = isAnagram("Angle","Angle");
System.out.println("Are Angle and Angel anangrams: "+isAnagram);
}
public static boolean isAnagram(String str1, String str2) {
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;
}
}
package org.TechtwitterCloud;
public class AnagramCountingMain {
public static void main(String args[])
{
boolean isAnagram = isAnagram("Angle","Angle");
System.out.println("Are Angle and Angel anangrams: "+isAnagram);
}
public static boolean isAnagram(String str1, String str2) {
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;
}
}class AnagramChecker:
@staticmethod
def is_anagram(s1: str, s2: str) -> bool:
s1 = s1.lower()
s2 = s2.lower()
if len(s1) != len(s2):
return False
count = {}
for ch in s1:
count[ch] = count.get(ch, 0) + 1
for ch in s2:
if ch not in count or count[ch] == 0:
return False
count[ch] -= 1
return True
if __name__ == "__main__":
print(AnagramChecker.is_anagram("Angel", "Angle"))
class AnagramChecker:
@staticmethod
def is_anagram(s1: str, s2: str) -> bool:
s1 = s1.lower()
s2 = s2.lower()
if len(s1) != len(s2):
return False
count = {}
for ch in s1:
count[ch] = count.get(ch, 0) + 1
for ch in s2:
if ch not in count or count[ch] == 0:
return False
count[ch] -= 1
return True
if __name__ == "__main__":
print(AnagramChecker.is_anagram("Angel", "Angle"))
Solution_5 : Using Sorting (Simple & Fast)
Solution_5 : Using Sorting (Simple & Fast)
This approach has time complexity of O(n), but it requires extra space for count Array.
import java.util.Arrays;
public class AnagramChecker {
public static boolean isAnagram(String str1, String str2) {
if (str1 == null || str2 == null || str1.length() != str2.length()) {
return false;
}
char[] a = str1.toLowerCase().toCharArray();
char[] b = str2.toLowerCase().toCharArray();
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a, b);
}
public static void main(String[] args) {
String s1 = "Angel";
String s2 = "Angle";
System.out.println(s1 + " and " + s2 +
" are anagrams: " + isAnagram(s1, s2));
}
}
import java.util.Arrays;
public class AnagramChecker {
public static boolean isAnagram(String str1, String str2) {
if (str1 == null || str2 == null || str1.length() != str2.length()) {
return false;
}
char[] a = str1.toLowerCase().toCharArray();
char[] b = str2.toLowerCase().toCharArray();
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a, b);
}
public static void main(String[] args) {
String s1 = "Angel";
String s2 = "Angle";
System.out.println(s1 + " and " + s2 +
" are anagrams: " + isAnagram(s1, s2));
}
}Solution_6: Frequency Map (HashMap / Dictionary)
import java.util.HashMap; import java.util.Map; public class AnagramFrequencyMap { public static boolean isAnagram(String s1, String s2) { if (s1 == null || s2 == null || s1.length() != s2.length()) { return false; } Map<Character, Integer> map = new HashMap<>(); // Count characters from first string for (char ch : s1.toCharArray()) { map.put(ch, map.getOrDefault(ch, 0) + 1); } // Decrease count using second string for (char ch : s2.toCharArray()) { if (!map.containsKey(ch)) { return false; } map.put(ch, map.get(ch) - 1); if (map.get(ch) == 0) { map.remove(ch); } } return map.isEmpty(); } public static void main(String[] args) { System.out.println(isAnagram("listen", "silent")); // true } }
class AnagramFrequencyMap: @staticmethod def is_anagram(s1: str, s2: str) -> bool: if len(s1) != len(s2): return False freq = {} # Count characters from first string for ch in s1: freq[ch] = freq.get(ch, 0) + 1 # Decrease count using second string for ch in s2: if ch not in freq: return False freq[ch] -= 1 if freq[ch] == 0: del freq[ch] return not freq if __name__ == "__main__": print(AnagramFrequencyMap.is_anagram("listen", "silent")) # TrueFinal comparison
Approach Time Complexity Space Complexity Best Use String methods (indexOf + substring) O(n²) O(n) ❌ Avoid – inefficient Sorting (Arrays.sort / sorted) O(n log n) O(n) 👍 Simple & readable Frequency Count (array) O(n) O(1) ⭐ Best & optimal Frequency Map (HashMap / Dictionary) O(n) O(k) 🌍 Best for Unicode Built-in APIs (Java 8 streams / Python Counter) O(n log n) O(n) ✔ Clean but not optimal