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’..}
  2. For every city (except for the first), check if exists in the map. If it does, update the result array
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()]
result[origMapIndex].append(city)
continue
rotatedCities = rotateString(city.lower())
# add rotated items to map
anagramMap = {**anagramMap,**{i: index for i in rotatedCities}}
return result

Engineering @Flipkart