Valid Anagram
Problem statement
You are given two strings s and t made of lowercase English letters. Return true if t uses exactly the same letters as s, each the same number of times, just possibly in a different order. Otherwise return false.
Examples
Example 1
Input: s = "listen", t = "silent"
Output: true
Explanation: Both contain one each of e, i, l, n, s, t.
Example 2
Input: s = "deploy", t = "depots"
Output: false
Explanation: s has l and y, t has t and s instead.
Hints
Approach
Count letters instead of sorting them. Add one for every letter of s, subtract one for every letter of t. If the strings are anagrams, every counter ends at zero.
- If the lengths differ, return
false. - Make 26 counters, one per letter.
- Increment for each letter in
s. - Decrement for each letter in
t. If a counter goes below zero,thas more of that letter thans, so returnfalse. - Return
true.
Because the lengths are equal, no counter can stay positive without another going negative, so step 4 catches every mismatch. The 26-slot array is fixed size, so the extra space is O(1).
O(n)Space O(1)class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False counts = [0] * 26 for ch in s: counts[ord(ch) - ord("a")] += 1 for ch in t: i = ord(ch) - ord("a") counts[i] -= 1 if counts[i] < 0: return False return TrueFollow-up questions
- Group a whole list of words into sets of anagrams.
- Find every position in a long string where an anagram of a short string starts.
Frequently asked questions
The fixed 26-slot array no longer fits. Use a hash map from character to count instead (Counter in Python, HashMap<Character, Integer> in Java). The time stays O(n), and the space grows with the number of distinct characters.
Yes, it is O(n) and clear. Be ready to explain what it does underneath, because the interviewer usually wants to see the counting idea.
Comparing two collections while ignoring order is common: checking that two hosts have the same set of installed packages, or that a new config has the same keys as the old one. Counting by key is the same technique.