Problem
Given two strings, decide whether one is a rearrangement of the other's letters.
Original: LeetCode 242: Valid Anagram.
Examples
Example 1
`s = "anagram", t = "nagaram"``true`Example 2
`s = "rat", t = "car"``false`Example 3
`s = "a", t = "ab"``false`Constraints
1 <= s.length, t.length <= 5 * 10^4sandtconsist of lowercase English letters.
Hints
Hint 1
"Anagram" means the same letters with the same counts. Order doesn't matter. Ask which characters can appear: the base problem uses lowercase English letters.
Hint 2
"Same characters, same counts" is frequency counting. With a small fixed alphabet, an int array is simpler and faster than a map.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Sort both strings and compare them: O(n log n). That is acceptable, but it isn't the best answer.
Optimal. One count array: add for s, subtract for t, and require all zeros. Check the lengths first, so mismatched lengths exit immediately.
Alternative. Use a HashMap of code points for full Unicode. String.codePoints() handles characters outside the Basic Multilingual Plane, which charAt splits into two chars.
Complexity
- Time
- O(n)
O(n) time. O(1) extra space, because the array has a fixed size of 26.
- Space
- O(1)
Code
public class ValidAnagram {
static boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
var count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
count[t.charAt(i) - 'a']--;
}
for (int c : count) {
if (c != 0) return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isAnagram("anagram", "nagaram")); // true
System.out.println(isAnagram("rat", "car")); // false
System.out.println(isAnagram("a", "ab")); // false
}
}Edge cases
- Different lengths.
- Empty strings, which count as anagrams of each other.
- Characters outside a to z, which would break the array index: confirm the alphabet first.
Follow-ups
- Unicode input: use a map of code points.
- Group many words by anagram: see Group Anagrams below.
- Find every anagram of a pattern inside a text: use a fixed sliding window.
Interview script
"If the lengths differ, it's false. Otherwise I count letters in an int array of 26, plus for s and minus for t, and check that everything returns to zero. O(n) time and constant space. For Unicode I'd use a map of code points."
Source: LeetCode 242: Valid Anagram Source: Java SE 17 API: String.codePoints)
Sources (2)
- LeetCode 242: Valid Anagramleetcode.com
- Java SE 17 API: String.codePointsdocs.oracle.com