You are given two strings and need to decide whether one is an anagram of the other.
That means they must contain exactly the same characters with exactly the same counts. The order does not matter, but the frequency does. If one string has an extra letter or is missing a copy of some letter, the answer is false.
For example, s = "anagram" and t = "nagaram" return true because both strings use the same letters the same number of times. But s = "rat" and t = "car" return false because the letters do not match.
So the task is to compare the full character inventory of both strings, not their order.
For Unicode strings or case-insensitive anagrams, a general hash map is needed instead of the fixed-size array. The hash map approach works for any character set.
An alternate solution sorts both strings and compares them. If the sorted versions are equal, they are anagrams. This runs in O(n log n) time compared to the hash map approach's O(n), but uses O(1) space (depending on the sorting algorithm).
Example Input & Output
Both strings contain the same letters with the same counts.
The letters do not match.
The character counts are different.
Algorithm Flow
Solution Approach
Count the frequency of each character in both strings and compare the frequency maps. If they are identical, the strings are anagrams.
Count characters in the first string using a frequency map. Then iterate through the second string, decrementing counts. If any character is missing or has an extra occurrence, the strings are not anagrams.
Time complexity is O(n), space complexity is O(k) where k is the alphabet size.
Best Answers
import java.util.*;
class Solution {
public boolean solution(String s, String t) {
if (s.length() != t.length()) return false;
int[] counts = new int[26];
for (char ch : s.toCharArray()) counts[ch - 'a']++;
for (char ch : t.toCharArray()) {
if (--counts[ch - 'a'] < 0) return false;
}
return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
