Valid Anagram in Java (LeetCode 242): Arrays
The first instinct most people have for LeetCode 242 (Valid Anagram) is to sort both strings and compare them. That works, but sorting costs you O(n log n) when the problem can actually be solved in a single straight pass through each string. Since both words only use lowercase English letters, a 26-slot counting array does the job in linear time, with no sorting step at all.
This post walks through why counting beats sorting here, dry-runs the logic on a couple of examples (including a sneaky one where the lengths differ), and then shares a clean Java implementation. There's also an interactive counter below so you can watch the 26 slots go up and down as each string is scanned.
Video Walkthrough
Prefer to watch it instead? Here's the full walkthrough, from reading the problem to submitting the solution:
1. What the Problem Asks
You're given two strings, s and t. The task is to check whether t is an anagram of s — meaning it uses exactly the same letters, the same number of times each, just possibly rearranged.
- Both strings contain only lowercase English letters, so there's no need to worry about case, punctuation, or spaces.
- If
sandtdon't have the same length, they can never be anagrams of each other — one is automatically missing or carrying extra letters. - Order doesn't matter at all. Only how many times each letter shows up matters.
The Core Idea: Count Up, Then Count Down
Instead of sorting both strings and comparing them character by character, keep a single 26-slot array — one slot per letter of the alphabet. Walk through s and increase the count for each letter you see. Then walk through t and decrease the count for each letter you see. If the two strings are true anagrams, every increase gets perfectly cancelled out by a matching decrease, and the array ends up back at all zeros. If even one slot isn't zero at the end, the letter counts didn't match up, so it can't be an anagram.
a[ch - 'a']++ counts go up
a[ch - 'a']-- counts go down
every slot == 0 anagram ✓
Every letter that went up while scanning s comes back down by exactly the same amount while scanning t, as long as both words share the same letter counts.
Quick Examples
Output: true
Why: Both strings use the exact same letters the exact same number of times, just in a different order.
Output: false
Why: "rat" has an 'r', 'a', 't'. "car" has a 'c' instead of a 't'. The counts don't cancel out.
2. Interactive Letter Counter
Step through both words below and watch each letter's count rise while scanning the first word, then fall while scanning the second.
3. Step-by-Step Code Walkthrough
Here's the logic behind the Java solution, broken into plain steps:
- Allocate a fixed counting array: We declare
int[] a = new int[26];, one slot for each lowercase letter. Java initializes every slot to0automatically. - Add for the first string: We loop through
sand incrementa[s.charAt(i) - 'a']for every character. - Subtract for the second string: We loop through
tand decrementa[t.charAt(i) - 'a']for every character. - Verify every slot returned to zero: If any slot in the array isn't exactly
0after both passes, the letter counts didn't match, so we returnfalse. If we get through all 26 slots cleanly, we returntrue.
The Java Solution
class Solution {
public boolean isAnagram(String s, String t) {
int[] a = new int[26];
for (int i = 0; i < s.length(); i++) {
a[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
a[t.charAt(i) - 'a']--;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != 0)
return false;
}
return true;
}
}
Test It Locally
Use this Main class to run a few test cases, including a pair with mismatched lengths:
public class Main {
public static boolean isAnagram(String s, String t) {
int[] a = new int[26];
for (int i = 0; i < s.length(); i++) {
a[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
a[t.charAt(i) - 'a']--;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != 0)
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isAnagram("anagram", "nagaram")); // true
System.out.println(isAnagram("rat", "car")); // false
System.out.println(isAnagram("listen", "silent")); // true
System.out.println(isAnagram("a", "ab")); // false
}
}
Console Output:
false
true
false
4. Complexity Analysis
- Time Complexity:
O(n), wherenis the length of the strings. We make one pass overs, one pass overt, and a final constant 26-step pass over the counting array. - Space Complexity:
O(1). The counting array is fixed at 26 slots no matter how long the input strings are.
5. Traps & Interview Tips
- Check the lengths first: If
s.length() != t.length(), the strings can never be anagrams, and you can returnfalseimmediately without touching the counting array at all. This isn't strictly required for correctness here (the final zero-check catches it anyway), but it's a cheap early exit worth mentioning in an interview. - Anagram vs. pangram: Don't confuse the two. A pangram checks whether a single sentence contains every letter of the alphabet at least once. An anagram compares two strings to see if they share identical letter counts.
- Why one array works instead of two: You could use two separate 26-slot arrays, one for each string, and compare them at the end. Using a single array with increments and decrements saves the comparison step entirely — zero everywhere means they already matched.
- Unicode input: This approach assumes lowercase English letters only, as the problem guarantees. If an interviewer extends the question to Unicode characters, a
HashMap<Character, Integer>replaces the fixed array, since you can no longer predict the character range in advance. - Related problems to practice:
- LeetCode 49 (Group Anagrams): Extends this same counting idea to group many strings together.
- LeetCode 1832 (Check if the Sentence Is Pangram): Uses the same 26-slot array technique, just checking presence instead of counts.
Comments
Post a Comment