Valid Anagram DSA Solution - Frequency Map - Study Chapter | QuizMaker

Valid Anagram explained with brute force sorting, optimized frequency map approach, dry run, edge cases, complexity, and Python, C++, Java code.

Read
9m
Type
Chapter
Access
Free

Course

DSA Course: Interview Patterns and Problem Solving

Topic

Module 2: Strings

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
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;

        unordered_map<char, int> counts;
        for (char ch : s) {
            counts[ch]++;
        }

        for (char ch : t) {
            if (counts[ch] == 0) return false;
            counts[ch]--;
        }

        return true;
    }
};
class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;

        Map<Character, Integer> counts = new HashMap<>();
        for (char ch : s.toCharArray()) {
            counts.put(ch, counts.getOrDefault(ch, 0) + 1);
        }

        for (char ch : t.toCharArray()) {
            int count = counts.getOrDefault(ch, 0);
            if (count == 0) return false;
            counts.put(ch, count - 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

Interview Checklist

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.

Tags

Open on QuizMaker