1246. Rotation Family Pairs

Medium3.5 points estimatedHash TableStringCounting3 hints

A cipher wheel spells a word by reading letters around a ring, so the same wheel can be read from any starting letter. You are given an array words of lowercase words. Two words belong to the same family when one can be turned into the other by moving some number of letters from the front to the back, which is a cyclic rotation. Every word is in a family with itself.

Return, as a long, the number of index pairs i < j whose words are in the same family. Identical words at different indices count as a pair, and words of different lengths never match. Key each word by its lexicographically smallest rotation and count the keys in a hash map. The intended solution runs in O(n * L^2) time and O(n * L) space, where n is the length of words and L the longest word.

Example 1

Input:
words = ["xyzy","yzyx","zyxy","yxyz","xyyz","pqrs","rspq"]
Output:
7
Explanation:

The four rotations of xyzy form 6 pairs and pqrs with rspq adds one more, for 7; the word xyyz is not a rotation of them.

Example 2

Input:
words = ["kiwi","wiki","iwik","ikiw","kiiw","mango","gomna"]
Output:
6
Explanation:

The words kiwi, wiki, iwik and ikiw are rotations of one another, giving 6 pairs, while kiiw, mango and gomna match nothing.

Example 3

Input:
words = ["lorem","remlo","ipsum","umips","dolor","lordo"]
Output:
3
Explanation:

Lorem with remlo, ipsum with umips, and dolor with lordo are the only rotation pairs, giving 3.

Constraints

  • 1 ≤ words.length ≤ 500

  • 1 ≤ words[i].length ≤ 20

  • words[i] consists of lowercase English letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n * L^2)
Space
O(n * L)

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…