Cyclic Number Pairs
A cyclic rotation of a number moves some of its trailing digits to the front, keeping the order of the rest: 5604 rotates to 4560, 456 rotates to 645 and 564. Moving zero digits leaves the number unchanged.
Given an array a of positive integers, count the pairs of indices i < j such that a[i] and a[j] have the same number of digits and one is a cyclic rotation of the other. Equal values at different indices form a pair.
countCyclicPairs([13, 5604, 31, 2, 13, 4560, 546, 654, 456]) -> 5 // (13, 31), (13, 13), (31, 13), (5604, 4560), (546, 654) // 546 and 456 are not rotations; 4560 and 456 differ in length
Up to 100,000 numbers, each at most 1,000,000,000.
Hints
Hint 1
Comparing every pair is 5 * 10^9 comparisons. Find something to compute per number so that rotations of each other get the same result.
Hint 2
All rotations of a string form one set. Pick a representative of that set, for example the lexicographically smallest rotation.
Hint 3
Keep rotations as strings of the original length. 4560 rotates to 0456, which is not the number 456.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.