Valid Anagram
Easy About 10 min Free, no account needed
Decide whether two strings are anagrams of each other.
The brief
Given two strings s and t, return true if t is an anagram of s,
the same characters with the same counts, in any order.
- Comparison is case-sensitive and includes every character.
- Two empty strings are anagrams of each other.
The obvious approach "crosses off" each character of s by scanning and removing it from
a copy of t. Every removal scans and shifts the remaining characters, so the
whole check is O(n2) with heavy copying. The hidden test compares two
50,000-character strings, where the quadratic version is far too slow. You need to decide
it in O(n).
Starter code
using System;
public class Solution
{
// TODO: return true when t contains exactly the same characters as s, with the same counts.
public bool AreAnagrams(string s, string t)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
What it practices
- Hash maps and sets
- Trade memory for constant-time lookups, membership tests and frequency counts.
Related katas
- Contains Duplicate Easy Free Decide whether an array contains any repeated value.
- Count Distinct Letters Easy Free How many different letters appear? A 26-slot array already knows.
- Count Pairs With Difference K Easy Free Count the pairs of indices whose values differ by exactly k.
- Isomorphic Strings Easy Free Can one string be turned into the other by a consistent character substitution?