Valid Anagram
Solve this Problems and t, return true if t is an anagramAnagramA word or phrase formed by rearranging the letters of another, using all the original letters exactly once. of s, and false otherwise.
Both strings consist only of lowercase English letters. Two strings are anagrams of each other only if they contain the exact same letters with the exact same frequency — order doesn't matter.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ s.length, t.length ≤ 5 × 10⁴ - ◆
s and t consist of lowercase English letters only
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public boolean isAnagram(String s, String t) { |
| 3 | if (s.length() != t.length()) return false; |
| 4 | Map<Character, Integer> freq = new HashMap<>(); |
| 5 | for (char c : s.toCharArray()) { |
| 6 | freq.put(c, freq.getOrDefault(c, 0) + 1); |
| 7 | } |
| 8 | for (char c : t.toCharArray()) { |
| 9 | if (!freq.containsKey(c) || freq.get(c) == 0) return false; |
| 10 | freq.put(c, freq.get(c) - 1); |
| 11 | } |
| 12 | return true; |
| 13 | } |
| 14 | } |
| 15 |
33First, check that both strings are the same length. s has 3 characters, t has 3 — they match, so an anagram is still possible.
Approach & Solutions
Brute Force — Sorting
BruteSort both strings alphabetically, then compare them character by character. If two strings contain exactly the same letters with the same frequency, sorting will line them up identically. Simple and correct, but the sort costs more than a single pass needs to.
O(n log n)O(n)1class Solution {
2 public boolean isAnagram(String s, String t) {
3 if (s.length() != t.length()) return false;
4 char[] sArr = s.toCharArray();
5 char[] tArr = t.toCharArray();
6 Arrays.sort(sArr);
7 Arrays.sort(tArr);
8 return Arrays.equals(sArr, tArr);
9 }
10}Optimal — Frequency Map
OptimalBuild a frequency map counting every character in s. Then walk through t, decrementing the count for each character you see. If a character in t is missing from the map, or its count is already zero, the strings can't be anagrams — bail out immediately. A single pass over each string, no sorting required.
O(n)O(n)1class Solution {
2 public boolean isAnagram(String s, String t) {
3 if (s.length() != t.length()) return false;
4 Map<Character, Integer> freq = new HashMap<>();
5 for (char c : s.toCharArray()) {
6 freq.put(c, freq.getOrDefault(c, 0) + 1);
7 }
8 for (char c : t.toCharArray()) {
9 if (!freq.containsKey(c) || freq.get(c) == 0) return false;
10 freq.put(c, freq.get(c) - 1);
11 }
12 return true;
13 }
14}