← Back to libraryQuestion 58 of 273
⌨️Java CodingIntermediate

Check if Two Strings are Anagrams

📌 Definition:

Two strings are anagrams if they contain the same characters with the same frequencies, in any order ("listen" / "silent").

📖 Detailed Explanation:

Either sort both and compare (O(n log n)), or count character frequencies and compare (O(n)). The counting approach is preferred at scale: increment for string A, decrement for B, then verify all counts are zero. A length check is a cheap early exit.

💻 Solutions:
public static boolean isAnagram(String a, String b) {
    if (a.length() != b.length()) return false;
    int[] f = new int[256];
    for (int i = 0; i < a.length(); i++) { f[a.charAt(i)]++; f[b.charAt(i)]--; }
    for (int x : f) if (x != 0) return false;
    return true;
}
function isAnagram(a, b) {
  if (a.length !== b.length) return false;
  const norm = str => str.split('').sort().join('');
  return norm(a) === norm(b);
}
from collections import Counter

def is_anagram(a, b):
    return Counter(a) == Counter(b)
🔑 Key Points:
  • Length must match first
  • Sort-and-compare: O(n log n)
  • Frequency count: O(n)
  • Clarify case/whitespace/unicode
🌍 Real-World Example:

Frequency comparison is how you assert two collections hold the same items regardless of order — a very common data check.

🎯 Scenario-Based Interview Question:

Inputs can be up to a million characters. Sort-and-compare or frequency count, and why?