Valid Anagram

Check whether two strings are anagrams — letter-count comparison.

Easy
Time O(N) Space O(1)
LeetCode
3 min read
hash-map counting strings

Problem#

Return true iff strings s and t contain the same letters with the same frequencies (i.e., one is an anagram of the other).

Examples#

  • s = "anagram", t = "nagaram"true.
  • s = "rat", t = "car"false.

Constraints#

  • 1 <= s.length, t.length <= 5 * 10^4, lowercase letters.

Hints#

Hint
Count letters of one string up, the other down — if every count returns to zero, they match.

Approach#

Single counter array cnt[26]. Increment for s, decrement for t. After the pass, all entries must be 0. Bail early if lengths differ.

Solution#

Valid Anagram
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int cnt[26] = {0};
for (int i = 0; i < (int)s.size(); ++i) { ++cnt[s[i] - 'a']; --cnt[t[i] - 'a']; }
for (int v : cnt) if (v != 0) return false;
return true;
}
};

Editorial#

The increment-then-decrement trick avoids two passes. Length mismatch catches the only case where balanced counts could lie (otherwise impossible — sum is zero iff counts match).

Complexity#

  • Time: O(N).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.