Valid Anagram

Easy
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Valid Anagram

Approach

Count character frequencies of the first string using a hash map. Then subtract frequencies using the second string. If any character count goes below zero or a character is missing, the strings are not anagrams. Equal lengths with matching frequencies confirms an anagram.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Frequency Count

Why It Works

Two strings are anagrams if and only if they have identical character frequency distributions. Incrementing for one string and decrementing for the other detects any mismatch.

Updated Feb 2026