# LeetCode: Valid Anagram Solution

## Approach 1

Sort strings and compare

Time complexity:

O(nlog(n))

## Implementation

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var isAnagram = function (s, t) {2  const sortString = str =>3    str4      .split("")5      .sort((a, b) => a.localeCompare(b))6      .join("")7  return sortString(s) === sortString(t)8}`

## Approach 2

Alphabetically count and compare

Time complexity:

O(n)

## Implementation

```1var isAnagram = function (s, t) {2  const [countS, countT] = [new Uint16Array(26), new Uint16Array(26)]3
4  for (let char of s) {5    countS[char.charCodeAt(0) - "a".charCodeAt(0)] += 16  }7
8  for (let char of t) {9    countT[char.charCodeAt(0) - "a".charCodeAt(0)] += 110  }11
12  for (let i = 0; i < 26; i++) {13    if (countS[i] !== countT[i]) {14      return false15    }16  }17
18  return true19}```

Original problem

## Similar problems

Group Anagrams

Palindrome Permutation

Find All Anagrams in a String

Find Resultant Array After Removing Anagrams

leetcode

neetcode

string

hash table

sorting

## Next Post

LeetCode: Longest Common Prefix

Feb 5, 2021

Search Posts