Valid Anagram
EasyGiven two strings s and t, return true if t is an anagram of s. An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once.
Examples
| Input | Output |
|---|---|
| s = "anagram", t = "nagaram" | true |
| s = "rat", t = "car" | false |
Python Solution
def is_anagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
counts = {}
for c in s:
counts[c] = counts.get(c, 0) + 1
for c in t:
counts[c] = counts.get(c, 0) - 1
if counts[c] < 0:
return False
return TrueJavaScript Solution
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const counts = {};
for (const c of s) counts[c] = (counts[c] || 0) + 1;
for (const c of t) {
counts[c] = (counts[c] || 0) - 1;
if (counts[c] < 0) return false;
}
return true;
}Step-by-Step Explanation
- Count character frequencies in s.
- For each character in t, decrement the count.
- If any count goes negative, t has extra characters—not an anagram.
Complexity Analysis
| Time | O(n) |
| Space | O(1) — at most 26 letters |
Tags
StringHash Map
Related Problems
Related Tools
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix