</>

242. Valid Anagram

Easy NeetCode 150
Arrays & Hashing Time O(n) Space O(1)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Arrays & Hashing
Time
O(n)
Space
O(1)

Standard Solution (C++)

SummaryDecide whether two strings are anagrams of each other, meaning one is a rearrangement of the other's characters with identical counts.

Approach

Count the frequency of each character in the first string, then decrement those counts while scanning the second string.

  • If the lengths differ, they cannot be anagrams.
  • Use a 26-slot array (lowercase letters) as a counter.
  • After processing both strings, every count must be zero.
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        int count[26] = {0};
        for (char c : s) count[c - 'a']++;
        for (char c : t) {
            if (--count[c - 'a'] < 0) return false;
        }
        return true;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern