Created
July 14, 2021 10:09
-
-
Save ali-master/cda37e7a1e30278832f321e8f8b0e2a6 to your computer and use it in GitHub Desktop.
Given an array of strings, group anagrams together in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This problem was asked by Robinhood. | |
Given an array of strings, group anagrams together. | |
For example, given the following array: | |
['eat', 'ate', 'apt', 'pat', 'tea', 'now'] | |
Return: | |
[['eat', 'ate', 'tea'], | |
['apt', 'pat'], | |
['now']] | |
TimeComplexity: o(n^2) | |
*/ | |
export function findAnagramGroups<Input extends Array<string>>(list: Input): Array<Input> { | |
const anagramsDictionary: Array<Input> = []; | |
const processed: Record<string, boolean> = {} | |
for (let i = 0; i < list.length; i++) { | |
const wordI = list[i]; | |
for (let j = i + 1; j < list.length; j++) { | |
const wordJ = list[j]; | |
if(isAnagram(wordI, wordJ)) { | |
if(anagramsDictionary[i] && !anagramsDictionary[j]) { | |
anagramsDictionary[i].push(wordJ); | |
}else { | |
if(!processed.hasOwnProperty(wordJ)) { | |
anagramsDictionary[i] = [wordI, wordJ] as Input; | |
} | |
} | |
processed[wordI] = true; | |
processed[wordJ] = true; | |
} | |
} | |
if(!processed[wordI]) { | |
anagramsDictionary[i] = [wordI] as Input; | |
} | |
} | |
return anagramsDictionary.filter(Boolean); | |
} | |
function isAnagram(str1: string, str2: string): boolean { | |
return sortAndClean(str1) === sortAndClean(str2); | |
} | |
function sortAndClean(str: string): string { | |
return str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment