Java Program to Check Anagram with Example
Arrays.sort() and Arrays.equals(), like this: Arrays.sort(charArray1); Arrays.sort(charArray2); return Arrays.equals(charArray1, charArray2);.Examples
How to Think About It
Algorithm
Code
import java.util.Arrays; public class AnagramCheck { public static boolean areAnagrams(String s1, String s2) { s1 = s1.replaceAll("\\s", "").toLowerCase(); s2 = s2.replaceAll("\\s", "").toLowerCase(); if (s1.length() != s2.length()) return false; char[] arr1 = s1.toCharArray(); char[] arr2 = s2.toCharArray(); Arrays.sort(arr1); Arrays.sort(arr2); return Arrays.equals(arr1, arr2); } public static void main(String[] args) { String str1 = "listen"; String str2 = "silent"; if (areAnagrams(str1, str2)) { System.out.println("The strings are anagrams."); } else { System.out.println("The strings are not anagrams."); } } }
Dry Run
Let's trace the example strings "listen" and "silent" through the code.
Input strings
s1 = "listen", s2 = "silent"
Remove spaces and lowercase
s1 = "listen", s2 = "silent" (no spaces, already lowercase)
Check length
Both lengths are 6, continue
Convert to char arrays
arr1 = ['l','i','s','t','e','n'], arr2 = ['s','i','l','e','n','t']
Sort arrays
arr1 = ['e','i','l','n','s','t'], arr2 = ['e','i','l','n','s','t']
Compare arrays
Arrays are equal, return true
| Step | arr1 | arr2 | Equal? |
|---|---|---|---|
| Before sort | ['l','i','s','t','e','n'] | ['s','i','l','e','n','t'] | No |
| After sort | ['e','i','l','n','s','t'] | ['e','i','l','n','s','t'] | Yes |
Why This Works
Step 1: Normalize strings
Removing spaces and converting to lowercase ensures the comparison ignores case and spaces.
Step 2: Sort characters
Sorting the characters puts letters in order, so anagrams will have identical sorted arrays.
Step 3: Compare sorted arrays
If the sorted arrays match exactly, the strings are anagrams; otherwise, they are not.
Alternative Approaches
public static boolean areAnagramsCount(String s1, String s2) { s1 = s1.replaceAll("\\s", "").toLowerCase(); s2 = s2.replaceAll("\\s", "").toLowerCase(); if (s1.length() != s2.length()) return false; int[] count = new int[26]; for (int i = 0; i < s1.length(); i++) { count[s1.charAt(i) - 'a']++; count[s2.charAt(i) - 'a']--; } for (int c : count) { if (c != 0) return false; } return true; }
import java.util.HashMap; public static boolean areAnagramsMap(String s1, String s2) { s1 = s1.replaceAll("\\s", "").toLowerCase(); s2 = s2.replaceAll("\\s", "").toLowerCase(); if (s1.length() != s2.length()) return false; HashMap<Character, Integer> map = new HashMap<>(); for (char c : s1.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for (char c : s2.toCharArray()) { if (!map.containsKey(c)) return false; map.put(c, map.get(c) - 1); if (map.get(c) < 0) return false; } return true; }
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting both strings takes O(n log n) time where n is the length of the strings, which dominates the runtime.
Space Complexity
Extra space is used for character arrays and sorting, which is O(n).
Which Approach is Fastest?
Counting characters with arrays is O(n) and faster for alphabets, but sorting is simpler and works for all characters.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting and comparing | O(n log n) | O(n) | General use, any characters |
| Counting with frequency array | O(n) | O(1) | Only alphabets, very fast |
| HashMap counting | O(n) | O(n) | Any characters, including unicode |