Skip to content

Valid Anagram

Solve on LeetCodeEasy
Time
Space

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Constraints:

  • 1≤1 \le s.length, t.length ≤5×104\le 5 \times 10^4
  • s and t consist of lowercase English letters.

Follow-up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Two strings are anagrams exactly when every letter occurs the same number of times in both. Sorting both strings and comparing works in O(nlog⁡n)O(n \log n), but with only 26 possible letters we can simply count.

One array is enough: add 1 for each letter of s and subtract 1 for each letter of t. The strings are anagrams if and only if every counter ends at 0 — a positive counter means s has a letter more often than t, a negative one the opposite.

  1. If s.size() != t.size(), return false (different lengths can never match).
  2. For each index i: count[s[i] - 'a']++ and count[t[i] - 'a']--.
  3. Return true if every entry of count is 0, otherwise false.
  • Time: O(n)O(n) — one pass over the strings plus a 26-entry check.
  • Space: O(1)O(1) — a fixed array of 26 counters.
  • Different lengths ("a", "ab"): rejected immediately by the length check, which also keeps t[i] in range in the loop.
  • Same letters, different counts ("aab", "abb"): the counters for a and b end at +1 and -1.

With Unicode the alphabet is no longer 26 letters, so replace the array by a hash map from code point to count (unordered_map<char32_t, int>), after decoding both strings from UTF-8 into code points. The algorithm and its O(n)O(n) time stay the same; the space becomes O(k)O(k) for kk distinct characters. If the text may contain composed and decomposed forms of the same character (e.g. é vs e + combining accent), normalise both strings (for example to NFC) first.

Think before you peek

Work out an approach on your own first — the explanation will still be here when you want it.

class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
array<int, 26> count{};
for (size_t i = 0; i < s.size(); i++) {
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for (int c : count)
if (c != 0) return false;
return true;
}
};
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] 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;
}
}
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26
for a, b in zip(s, t):
count[ord(a) - ord('a')] += 1
count[ord(b) - ord('a')] -= 1
return not any(count)

Give it a try first

Attempt the problem on LeetCode — the code will still be here.