Problem
You are given two stringss and t.
Return
true if t is an anagram of s. Otherwise, return false.
An anagram is formed by rearranging all the characters of a string. Therefore, both strings must contain the same characters with the same frequencies.
Example(s)
Consider the following example(s) to understand the expected input and output.Input
s = "anagram" t = "nagaram"
Output
true
Both strings contain the same characters with the same frequencies, only their order is different.
Solution
This problem can be solved using a character frequency array.First, if the two strings have different lengths, they cannot be anagrams because an anagram must contain exactly the same number of characters.
We then maintain a frequency count for each character. For every character in
s, we increase its count, and for every character in t, we decrease its count.
If the strings are anagrams, every character's count will eventually become
0. If any count is not 0, the strings contain different character frequencies.
class Solution {
public boolean isAnagram(String s, String t) {
// Anagrams must have the same length.
if (s.length() != t.length()) {
return false;
}
int[] frequency = new int[26];
for (int i = 0; i < s.length(); i++) {
// Count characters from s.
frequency[s.charAt(i) - 'a']++;
// Remove characters from t.
frequency[t.charAt(i) - 'a']--;
}
// Every character must have the same frequency.
for (int count : frequency) {
if (count != 0) {
return false;
}
}
return true;
}
}
Complexity
Each character is processed once, and the frequency array contains only26 entries, resulting in O(n) time complexity and O(1) space complexity.