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 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)]34 for (let char of s) {5 countS[char.charCodeAt(0) - "a".charCodeAt(0)] += 16 }78 for (let char of t) {9 countT[char.charCodeAt(0) - "a".charCodeAt(0)] += 110 }1112 for (let i = 0; i < 26; i++) {13 if (countS[i] !== countT[i]) {14 return false15 }16 }1718 return true19}
References
Similar problems
Palindrome Permutation
Find All Anagrams in a String
Find Resultant Array After Removing Anagrams
Comments
Loading comments...
Tags
leetcode
neetcode
string
hash table
sorting
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Longest Common Prefix
Feb 5, 2021
Previous Post
LeetCode: Implement Strstr
Feb 5, 2021