v9.1.1
Menu

Valid Anagram

easyFREEArrays & HashingBlind 75

Given two strings s and t, return True if t is an anagram of s, and False otherwise.

An anagram uses the exact same characters with the exact same frequencies.

Example

Input
anagram
nagaram
Output
True
Reasoning
  • Input: two lowercase strings, s = "anagram" and t = "nagaram". The question is whether the letters of tt are a rearrangement of the letters of ss, with order ignored entirely.
  • Tally the letters of ss: "anagram" has 7 letters, made up of a ×3\times 3, n ×1\times 1, g ×1\times 1, r ×1\times 1, m ×1\times 1 (and 3+1+1+1+1=73+1+1+1+1 = 7).
  • Tally the letters of tt: "nagaram" also has 7 letters, and its tally is again a ×3\times 3, n, g, r, m ×1\times 1 each. Every letter appears in both strings, and no letter's count differs.
  • Output: identical tallies mean tt uses exactly the same letters with exactly the same frequencies, so the answer is True.
  • Notice: contrast s = "rat", t = "car". Both have 3 letters, but tt has a c that ss lacks and is missing the t, so the answer is False. Equal length is necessary but not sufficient. Strings of different lengths can never be anagrams, since some letter's count must differ.

Constraints

  • 1 <= len(s), len(t) <= 5 * 10^4
  • s and t consist of lowercase English letters

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.