242. Valid Anagram

1. Description

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

2. Example

Example 1

Input: s = “anagram”, t = “nagaram”
Output: true

Example 2

Input: s = “rat”, t = “car”
Output: false

3. Constraints

  • 1 <= s.length, t.length <= 5 * 10$^{4}$
  • s and t consist of lowercase English letters.

4. Solutions

Hash Table

m = s.size(), n = t.size()
Time complexity: O(max(m, n))
Space complexity: O(1)

class Solution {
public:
    bool isAnagram(const string &s, const string &t) {
        if (s.size() != t.size()) {
            return false;
        }

        array<int, 26> count{};
        for (char c : s) {
            ++count[c - 'a'];
        }

        for (char c : t) {
            if (--count[c - 'a'] < 0) {
                return false;
            }
        }

        return true;
    }
};
comments powered by Disqus