Valid Anagram
Easy
Hash MapString
Problem
Given two strings s and t, return true if t is an anagram of s (same letters, possibly different order).
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
Constraints
- 1 ≤ s.length, t.length ≤ 5·10⁴
- s and t consist of lowercase English letters
Approach — Hashing & Counting
This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(n) space.
Solution code
Python
class Solution:
def isAnagram(self, s, t):
from collections import Counter
return Counter(s) == Counter(t)
Java
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
counts[s.charAt(i) - 'a']++;
counts[t.charAt(i) - 'a']--;
}
for (int count : counts) {
if (count != 0) {
return false;
}
}
return true;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Valid Anagram interactively → ← All solutions