Arrays & Hashing

Character Frequency Count

Valid Anagram

1Question

Valid Anagram

EasyLeetCode 242 ↗

You are given two strings s and t. Return true if t is an anagram of s, and false if it is not.

Rules

An anagram uses exactly the same letters, the same number of times, but the letters can be in any order. For example, "listen" and "silent" are anagrams.

Examples
Example 1
Input: s = "anagram", t = "nagaram"
Output: true

Both words have 3 a, 1 n, 1 g, 1 r and 1 m. Only the order is different.

Example 2
Input: s = "rat", t = "car"
Output: false

“rat” has a t, but “car” has a c instead. The letters are not the same.

Example 3
Input: s = "a", t = "ab"
Output: false

The lengths are different, so the letters can never match.

Constraints

1 ≤ s.length, t.length ≤ 5 × 104

Up to 50,000 letters. Sorting both strings is fast enough, but we can do it in O(n).

s and t use lowercase English letters

Only 26 possible letters (a to z). So a tiny array of 26 counters is enough.

Follow-up

What if the strings contain Unicode characters? Use a hash map instead of a fixed array of 26.

2Hints

Open one hint at a time. Try to think before you open the next one.

3Pattern

Pattern name

Character Frequency Count

Count how many of each item, and ignore the order.

When order does not matter, two collections are the same if every item has the same count. A hash map stores letter → count, so each update is one O(1) step:

count[ch] += 1 for ch in s; count[ch] −= 1 for ch in t

If all counts are 0 at the end, the two strings are made of the same letters.

How to spot this pattern

  • The question says “same letters”, “rearrange” or “anagram”.
  • The order of items does not matter, only how many of each.
  • The set of possible items is small (like 26 letters) or can be stored in a map.
  • You are allowed O(1) or O(n) extra memory.

4Explanation

The big idea: Use one counter called count (letter → number). Do two small jobs:

Step 1: Add

For every letter in s, do count[ch] += 1.

Step 2: Subtract

For every letter in t, do count[ch] −= 1.

Why does this work? If t has exactly the same letters as s, every +1 gets cancelled by one −1. So all counts end at 0.

Why check the length first? If the lengths are different, the counts can never all be 0. Returning false early saves work.

5Brute Force

Sort both strings and compare them.

Idea

If two strings are anagrams, then after sorting their letters they become identical. So we:

  • Sort the letters of s.
  • Sort the letters of t.
  • If the two sorted results are equal, return True.
Python
def is_anagram_brute(s, t):
    if len(s) != len(t):          # different lengths can never match
        return False

    return sorted(s) == sorted(t)  # same letters in the same order after sorting


print(is_anagram_brute("anagram", "nagaram"))  # True

6Optimal Solution

One hash map of letter → count.

Python
def is_anagram(s, t):
    if len(s) != len(t):
        return False

    count = {}                        # letter -> how many

    for ch in s:
        count[ch] = count.get(ch, 0) + 1     # add for s

    for ch in t:
        if count.get(ch, 0) == 0:     # t has a letter that s has no more of
            return False
        count[ch] -= 1                # subtract for t

    return True                       # equal lengths + no extra letter = anagram


print(is_anagram("anagram", "nagaram"))  # True

7Time and Space Complexity

Let n be the number of items in the array.

Brute force (sorting)

Time: O(n log n)Space: O(n)

Optimal (frequency count)

Time: O(n)Space: O(1)

How big is the difference?

Approximate number of steps:

nSorting (n log n)Counting (n)
10about 3310
1,000about 10,0001,000
50,000about 780,00050,000

For the biggest input in this problem, counting does around 15 times less work, and it does not need to copy the strings.

8Visualization

Try:Type two words (letters a-z, up to 12 each), separated by a comma.
Current Letter-
Letters Tracked-
Anagram?-
"anagram" "nagaram"

Step Analysis

Click "Next" to begin analysis.
Core Logic:
Letter of s: count[c] += 1
Letter of t: count[c] −= 1
Any count below 0? return False