Created
June 12, 2018 13:23
-
-
Save albinotonnina/e5eb9589f3a2322678b75461ac230181 to your computer and use it in GitHub Desktop.
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
/* | |
Problem: | |
['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris'] | |
// YOUR ALGORITHM | |
[ | |
[ 'Tokyo', 'Kyoto' ], | |
[ 'London', 'Donlon' ], | |
[ 'Rome' ], | |
[ 'Paris' ] | |
] | |
*/ | |
const getWordRotations = word => | |
[...word].reduce( | |
acc => [acc[0].substring(1) + acc[0].substring(0, 1), ...acc], | |
[word] | |
); | |
const groupCitiesByRotatedNames = cities => | |
cities.reduce((acc, city) => { | |
const cityGroup = acc.find(item => | |
getWordRotations(city.toLowerCase()).includes(item[0].toLowerCase()) | |
); | |
cityGroup | |
? acc.splice(acc.indexOf(cityGroup), 1, [...cityGroup, city]) | |
: acc.push([city]); | |
return acc; | |
}, []); | |
const test = groupCitiesByRotatedNames([ | |
"Tokyo", | |
"London", | |
"Rome", | |
"Donlon", | |
"Kyoto", | |
"Paris" | |
]); | |
console.log("test", test); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assuming
n
is the number of accesses to the cities array, you can achieve linear timeO(n)
using the following approach: