Valid Anagram
Problem information
- Leetcode problem: https://leetcode.com/problems/valid-anagram/description/
- Neetcode problem: https://neetcode.io/problems/is-anagram
- Difficulty: Easy
Solution
Two strings are anagrams if the sum of each of their letters is equal. Since there are 26 letters in the English alphabet, you can create an array to count the number of letters in one string, then substract the letters of the second string, if the count in each element of the array is zero, then both strings are a valid anagram.
- Time Complexity:
O(|s| + |t|) - Space Complexity
O(1)
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
int[] count = new int[26];
for (char c: s.toCharArray()) {
count[c - 'a']++;
}
for (char c: t.toCharArray()) {
count[c - 'a']--;
}
for (int i: count) {
if (i != 0)
return false;
}
return true;
}
}