InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Valid Anagram

easy Original ↗ 00:00

Problem

Given two strings s and t, return True if t is an anagram of s — that is, if t can be formed by rearranging the letters of s, using every letter exactly once — and False otherwise.

Examples

  • s = "anagram", t = "nagaram"True — same letters, same multiplicities (3×a, 1 each of n, g, r, m).
  • s = "rat", t = "car"Falset contains a c that s doesn’t have.
  • s = "ab", t = "abb"False — different lengths can never be anagrams.

Constraints

  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters.

Follow-up: what would you change if the inputs could contain any Unicode characters?

Think about it first

Hint 1 Two strings are anagrams exactly when some canonical form of each is identical. What canonical form ignores letter order?
Hint 2 Sorting works but costs O(n log n). Order doesn't actually matter — only how many times each letter appears. Can you compare that directly?
Hint 3 Count the 26 letter frequencies of each string (an array of 26 ints, or a `Counter`) and compare the two tallies — one pass over each string.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug