242. Valid Anagram#

Approach 1: Keeping Count Array#

 1public boolean isAnagram(String s, String t) {
 2  int[] charCount = new int[26];
 3
 4  for (char c : s.toCharArray()) {
 5    charCount[c - 'a']++;
 6  }
 7
 8  for (char c : t.toCharArray()) {
 9    charCount[c - 'a']--;
10  }
11
12  for (int count : charCount) {
13    if (count != 0) return false;
14  }
15
16  return true;
17}

Time Complexity

Space Complexity

\(\mathcal{O}(n)\)

\(\mathcal{O}(1)\)

Approach 2: Sorting#

1public boolean isAnagram(String s, String t) {
2  char[] sArray = s.toCharArray();
3  char[] tArray = t.toCharArray();
4
5  Arrays.sort(sArray);
6  Arrays.sort(tArray);
7
8  return Arrays.compare(sArray, tArray) == 0;
9}

Time Complexity

Space Complexity

\(\mathcal{O}(nlogn)\)

\(\mathcal{O}(n)\)