Skip to content

242. Valid Anagram 👍

  • Time: $O(n)$
  • Space: $O(128) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  bool isAnagram(string s, string t) {
    if (s.length() != t.length())
      return false;

    vector<int> count(128);

    for (const char c : s)
      ++count[c];

    for (const char c : t)
      if (--count[c] < 0)
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public boolean isAnagram(String s, String t) {
    if (s.length() != t.length())
      return false;

    int[] count = new int[128];

    for (final char c : s.toCharArray())
      ++count[c];

    for (final char c : t.toCharArray())
      if (--count[c] < 0)
        return false;

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def isAnagram(self, s: str, t: str) -> bool:
    if len(s) != len(t):
      return False

    dict = Counter(s)

    for c in t:
      dict[c] -= 1
      if dict[c] < 0:
        return False

    return True
Back to top