Example 1
ready- Input
s = "secure" t = "rescue"- Expected
true- Why
- both words use the same six letters
Two word-game tiles can look unrelated until you sort the letters in your hand.
An anagram is a rearrangement that uses every original character exactly once. Given
two strings s and t, return true when t is an anagram of s; otherwise, return
false.
Think in terms of a multiset: a collection where both the values and their repeat
counts matter. Order doesn't matter, but losing one a or gaining one z does.
A few ground rules:
1 <= s.length, t.length <= 50_000s and t consist only of lowercase English letters a through z.Hints
If you sort both strings, anagrams collapse to the same ordered sequence of letters. This gives you a clean baseline solution.
There are only 26 possible characters. Give each letter a counter, add the letters
from s, then subtract the letters from t.
First reject unequal lengths. After all additions and subtractions, every one of the 26 counters must be zero.
Can you solve it with one fixed 26-slot table, no matter how long the two strings become?
Visible cases
s = "secure"
t = "rescue"trues = "letter"
t = "teller"falses = "note"
t = "notes"falseInterview signal
Sorting removes the only difference an anagram is allowed to have: character order. Reject unequal lengths, sort both strings, and compare the results.
def is_anagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)Time O(n log n) for the two sorts. Space O(n) for the sorted character lists. This is a strong baseline, but it does more work than a 26-letter alphabet demands.
A frequency table stores how many times each possible value occurs. Here, index 0
stands for a, index 1 for b, and so on through index 25 for z.
Add each character from s to its slot and subtract each character from t. Equal
multisets cancel perfectly, leaving 26 zeroes.
def is_anagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
counts = [0] * 26
for char in s:
counts[ord(char) - ord("a")] += 1
for char in t:
counts[ord(char) - ord("a")] -= 1
return all(count == 0 for count in counts)The length check is more than a shortcut. It rules out extra characters before counting and lets both loops cover the same number of positions.
Time O(n), because each character is counted once. Space O(1), because the table always has exactly 26 slots rather than growing with the strings.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
true