May 2, 2022

Question 2 : Write a java program to check if two Strings are anagram in java?

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:
  1. Pass two Strings word and anagram to method called isAnagramUsingStringMethods()
  2. Iterate over first String word and get char c from it using charAt() method
  3. If index of char c is -1 in second String anagram, then two strings are not anagrams
  4. If index of char c is not equal to -1 in second String anagram, then remove the character from the String anagram.
  5. 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

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.

  1. Pass two Strings str1 and str2 to method isAnagram()
  2. If length of str1 and str2 are not same, then they are not anagrams
  3. Create an array named count of 256 length
  4. Iterate over first string str1
  5. In each iteration, we increment count of first String str1 and decrement the count of second String str2
  6. 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; } }

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)

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)); } }

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")) # True

Final 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

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS