pyassistant

Group strings by cyclic rotation

Given a list of lowercase strings, group indices of strings that are cyclic rotations of each other. Two strings are considered equivalent if one can be obtained from the other by a cyclic shift (rotation). Only strings of equal length can be rotations. Return a list of groups where each group is a sorted list of 1-based indices of equivalent strings. The groups should be ordered by the smallest index in each group (ascending). Strings that have no rotational equivalents still form a group containing their single index. Implement a function solve(words: list[str]) -> list[list[int]] that performs this grouping efficiently (linear time per string for finding canonical rotation is recommended).

Example:

Input:
(['bca', 'abc', 'cab', 'abcd', 'dabc', 'bcaa', 'aabc'])
Output:
[[1, 2, 3], [4, 5], [6, 7]]

Make sure you return your solution, don't print!

AI

Bot

Trying to solve my challenge? Ask if you must, or press the purple button so I can analyze your code.