LeetCode: Valid Anagram Solution

Approach 1

Sort strings and compare

Time complexity: O(nlog(n))

Implementation

1var isAnagram = function (s, t) {
2 const sortString = str =>
3 str
4 .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)] += 1
6 }
7
8 for (let char of t) {
9 countT[char.charCodeAt(0) - "a".charCodeAt(0)] += 1
10 }
11
12 for (let i = 0; i < 26; i++) {
13 if (countS[i] !== countT[i]) {
14 return false
15 }
16 }
17
18 return true
19}

References

Original problem

Similar problems

Group Anagrams

Palindrome Permutation

Find All Anagrams in a String

Find Resultant Array After Removing Anagrams

Comments

Loading comments...

Tags

leetcode

neetcode

string

hash table

sorting

Next Post

LeetCode: Longest Common Prefix

HoningJS

Search Posts