Algo-Sim › Arrays & Hashing
Valid Anagram
Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input
Is t a rearrangement of the letters of s? Count letters in a 26-slot frequency table.
Problem
Given two strings s and t, decide whether t uses exactly the same letters as s, each the same number of times, possibly in a different order. Return true or false.
Constraints
- 1 ≤ s.length, t.length ≤ 5 · 10⁴
- s and t contain only lowercase English letters
- Different lengths can never be anagrams
Edge cases to test
- Different lengths:
falsebefore counting - Same letters, different counts:
"aab"vs"abb" - Empty strings are anagrams of each other
Follow-up questions
- What if the input is Unicode, not just a–z?
- Count with a hash map keyed by code point instead of a 26-slot array: O(n) time, O(k) space for k distinct characters.
- Can you do it without the count table?
- Sort both strings and compare: O(n log n) time, O(1) extra if sorting in place.
Solution
Java
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;
}Python
def is_anagram(s, t):
if len(s) != len(t):
return False
count = [0] * 26
for i in range(len(s)):
count[ord(s[i]) - ord('a')] += 1
count[ord(t[i]) - ord('a')] -= 1
for c in count:
if c != 0:
return False
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isAnagram(string &s, string &t) {
if (int(s.size()) != int(t.size()))
return false;
vector<int> count = vector<int>(26);
for (int i = 0; i < int(s.size()); i++) {
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for (int c : count) {
if (c != 0)
return false;
}
return true;
}
};
More Arrays & Hashing problems
- Contains Duplicate (Easy)
- Two Sum (Easy)
- Group Anagrams (Medium)
- Top K Frequent Elements (Medium)
- Encode and Decode Strings (Medium)
- Product of Array Except Self (Medium)
- Longest Consecutive Sequence (Medium)
- Majority Element (Easy)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Subarray Sum Equals K (Medium)
- Design HashMap (Easy)