Skip to content

Valid anagram solution may need to be retweaked for C++ #2142

@Malcolmt129

Description

@Malcolmt129

After doing some debugging I found that the last for loop is not necessary in the C++ implementation. This is because it doesn't check the hashmap by index as the code may suggest. Instead it just adds another value into the hashmap. So instead of:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()) return false;
        
        unordered_map<char,int> smap;
        unordered_map<char,int> tmap;
        
        for(int i = 0; i < s.size(); i++){
            smap[s[i]]++;
            tmap[t[i]]++;
        }
        
        for(int i = 0; i < smap.size(); i++){
            if(smap[i] != tmap[i]) return false;
        }
        return true;
    } 

Maybe use:

class Solution {
public:
    bool isAnagram(string s, string t) {
     if (s.size() != t.size()) return false;
     
     unordered_map<char,int> smap;
     unordered_map<char,int> tmap;

     for (int i =0; i < s.size(); i++){
        smap[s[i]]++;
        tmap[t[i]]++; 
     }

    if (smap != tmap) return false;
     return true;

    }
};

This solution has been accepted also but it is important that new programmers don't think that you can access an unordered map in a similar way to an array in other languages.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions