1204. Rotation Families

Medium3.5 points estimatedHash TableStringTwo Pointers

A word-puzzle site groups words that are the same ring of letters read from a different starting point. Two words belong to the same family when one is a cyclic rotation of the other, so abc and cab match, while words of different lengths never do. Equal words are in the same family.

Return the number of distinct families in words. Replace every word by its lexicographically smallest rotation, found in linear time with a two-pointer scan that keeps two candidate starts and the length of their common run, and count the distinct results in a hash set.

Here 1 <= words.length <= 10^5, every word has at least one letter, the total length of all words is at most 2 * 10^5, and words use lowercase letters. The intended cost is O(total length) time and space.

Example 1

Input:
words = ["abc","bca","cab","bac"]
Output:
2
Explanation:

abc, bca and cab are rotations of each other, while bac is not a rotation of them, so there are 2 families.

Example 2

Input:
words = ["aa","aa","a"]
Output:
2
Explanation:

The two words aa are equal and a has a different length, so there are 2 families.

Example 3

Input:
words = ["abab","baba","aabb","abba","bbaa"]
Output:
2
Explanation:

abab and baba form one family; aabb, abba and bbaa form another.

Constraints

1 ≤ words.length ≤ 105

total length of all words is at most 2 * 105

words contain lowercase letters only

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(total length)
Space
O(total length)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…