Simple C++ solution (O(N) space, O(1) time)

  • 0
    class Solution {
        bool isAnagram(string s, string t) {
            vector<int> table(26,0);
            for(int i = 0; i < max(s.size(), t.size()); i++){
                if(i < t.size()) table['a']++;
                if(i < s.size()) table['a']--;
            for(int i = 0; i < table.size(); i++){
                if(table[i]) return false;
            return true;

    Don't forget that the constraint tells us to use only lowercase letters, this means we only need to use a size 26 array.

    This solution iterates over both strings in one loop, and increments/decrements the letter value index in my table. If there are any leftover characters, that means it is not an anagram (all letters should cancel out).

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.