Last active
June 26, 2019 17:04
-
-
Save leonidkuznetsov18/d6f3c850f8f9a666bd0bd5e619ce7403 to your computer and use it in GitHub Desktop.
Group Anagrams
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
/* | |
INPUT | |
anagrams(['xxy', 'cab', 'bca', 'cab', 'bac', 'baa', 'abb', 'dash', 'shad']) | |
OUTPUT | |
[ | |
['xxy'], | |
['cab', 'bca’, 'bac'], | |
['dash', 'shad'], | |
['abb'], | |
['baa'], | |
] | |
anagrams are words that can be rearranged to become the same word. | |
Group strings that are anagram of each other into a list without duplicate. | |
*/ | |
const sortString = (str) => { | |
return str.split("").sort().join(""); | |
} | |
const anagrams = (words) => { | |
if (!Array.isArray(words)) { | |
return null; | |
} | |
const uniqeArr = [... new Set(words)]; | |
const results = {}; | |
uniqeArr.forEach((el) => { | |
let sortedString = sortString(el); | |
if(results.hasOwnProperty(sortedString)) { | |
results[sortedString].unshift(el); | |
} else { | |
results[sortedString] = [el]; | |
} | |
}) | |
return Object.values(results); | |
} | |
const groupedAnagrams = anagrams(['xxy', 'cab', 'bca', 'baa', 'abb', 'cab', 'bac', 'dash', 'shad']); | |
console.log(groupedAnagrams); | |
const testCase1 = anagrams([]); | |
const testCase2 = anagrams('xxy', 'cab', 'sos'); | |
const testCase3 = anagrams('sos'); | |
const testCase4 = anagrams(['sos', 'lol', { sos: 'sos'}]); | |
const testCase5 = anagrams(['sos', 'lol', 'cab', '', 123]); | |
const testCase6 = anagrams(777); | |
const testCase7 = anagrams(['sos', 'lol', 'cab', 'zsc', 'scz', 'csz']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment