[
string
hash table
]
BinarySearch 0434 Rotation Groups
Problem statement
https://binarysearch.com/problems/Rotation-Groups/
Solution
For each string we can find its representative: minimum among all rotations.
Complexity
It is O(l1^2 + ... + ln^2)
for time, where l1, ..., ln
are lengths of words, space is O(l1 + ... + ln)
.
Code
class Solution:
def solve(self, words):
d = defaultdict(list)
for w in words:
d[min(w[i:] + w[:i] for i in range(len(w)))] += [w]
return len(d)
Remark
Notice, that we can find minimum rotation in O(l)
, which will make total time complexity O(l1 + ... + ln)
.