Skip to main content

Command Palette

Search for a command to run...

242. Valid Anagram

Published
1 min read

[EASY] Link: https://leetcode.com/problems/valid-anagram/description/

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

Example 1:

Input: s = “listen” , t = “silent” & s = “heart”, t = “earth” …

Output: True

Example 2:

Input: s = “hat”, t = “hit”

Output: False

1. Sort

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        for (int i = 0; i < max(s.size(), t.size()); i++)
        {
            if (t[i] != s[i]) return false;
        }   
        return true;
    }
};

2. Hash Map

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