Valid Anagram
The drill: Two lowercase words, one question: are they the same multiset of letters? Shuffling is free — what matters is that every letter shows up the same number of times on both sides.
Two lowercase strings arrive side by side, and the question is whether one is simply a rearrangement of the other's letters — same letters, same counts, order doesn't matter.
Every character in the first string must be accounted for somewhere in the second, with matching frequency; nothing may be added, dropped, or substituted along the way.
Strings of different lengths can never be anagrams of each other, which settles the answer immediately without inspecting a single letter.
- strings hold lowercase letters only, on the order of a few thousand characters at most
- differing lengths mean an automatic no
- letter order carries no meaning, only counts
- the answer is a single true/false verdict
HINT 1 THE NUDGE
Order is the only thing an anagram scrambles. What property of a word survives any shuffle completely untouched?
HINT 2 THE STRUCTURE
Force both words into one agreed-upon order and true rearrangements become identical strings — or skip ordering entirely and compare how often each letter appears.
HINT 3 ONE STEP FROM THE ANSWER
Lowercase means at most 26 letters. One 26-slot tally — add along s, subtract along t — and any nonzero slot ends the debate. A length check up front makes the quick exit free.
s = "race", t = "care" — same length 4, so a mismatch can't be ruled out by length alone.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = [0] * 26
for ch in s:
count[ord(ch) - ord("a")] += 1
for ch in t:
count[ord(ch) - ord("a")] -= 1
return all(c == 0 for c in count)class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
count[t.charAt(i) - 'a']--;
}
for (int c : count) {
if (c != 0) {
return false;
}
}
return true;
}
}class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char[] a = s.toCharArray();
char[] b = t.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
return Arrays.equals(a, b);
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED