Article start
DSA Course: Interview Patterns and Problem Solving
Module 2: Strings

Valid Anagram: Frequency map Pattern

Compare character frequencies to check whether two strings contain exactly the same letters.

May 28, 2026·28

Learning Outcome

After this lesson, you should be able to decide when sorting is enough and when a frequency map is the cleaner linear-time solution.

Problem Statement

Given two strings s and t, return true if t is an anagram of s. An anagram uses the same characters with the same frequencies.

InputOutputWhy
s = "anagram", t = "nagaram"trueBoth strings contain the same character counts.
s = "rat", t = "car"falseThe character counts differ.

Brute Force Approach

Sort both strings and compare the sorted results. If they match, the strings are anagrams.

This is simple and valid, but sorting costs O(n log n). If the character set is small or counting is natural, a frequency approach is better.

Optimized Approach

First reject strings of different lengths. Then count every character in s and subtract counts while scanning t. If a count goes below zero or a character is missing, the strings are not anagrams.

Exact Pseudocode

if length(s) != length(t):
  return false
counts = empty map
for char in s:
  counts[char] = counts[char] + 1
for char in t:
  if char not in counts or counts[char] == 0:
    return false
  counts[char] = counts[char] - 1
return true

Reference Code

class Solution:
    def isAnagram(self, s, t):
        if len(s) != len(t):
            return False

        counts = {}
        for ch in s:
            counts[ch] = counts.get(ch, 0) + 1

        for ch in t:
            if counts.get(ch, 0) == 0:
                return False
            counts[ch] -= 1

        return True

Sample Dry Run

StepActionState
Build counts from anagramCount each chara:3, n:1, g:1, r:1, m:1
Read n from nagaramSubtract 1n:0
Read remaining charsAll counts stay validNo missing or negative count
FinishReturntrue

Complexity

MeasureValueReason
TimeO(n)Each string is scanned once.
SpaceO(k)k is the number of distinct characters stored.

Edge Cases

  • Different lengths should immediately return false.
  • Repeated characters such as multiple a values.
  • Character set assumptions: lowercase English letters versus Unicode.

Interview Checklist

  • Ask whether input is lowercase English only.
  • Mention sorting as brute force or baseline.
  • Use frequency counts for linear time.

FAQs

Is sorting acceptable?

Yes, but it is O(n log n). Counting is usually better when character frequencies are enough.

Why check length first?

Strings of different lengths cannot have identical character frequencies.

What is the core pattern?

Frequency map comparison.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.