Hi Albino. Nice post. If my understanding is correct, we are looking for *anagram pairs in the array*. I tried my own solution. It takes more space but easier on the time complexity. Here’s how

  1. For every city, put its rotated cities in a dict with key as rotated city and the value as the original city. For eg.
    for ‘Tokyo’: {‘okyot’ -> ‘Tokyo’, ‘kyoto’: ‘Tokyo’, ‘yotok’:‘Tokyo’..}
def groupCitiesByRotatedName(A):
"""Groups cities by anagram pairs"""
result = [[city] for city in A]
anagramMap = {}
for index, city in enumerate(A):
if city.lower() in anagramMap:
origMapIndex = anagramMap[city.lower()]
rotatedCities = rotateString(city.lower())
# add rotated items to map
anagramMap = {**anagramMap,**{i: index for i in rotatedCities}}
return result



Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store