← Questions

Count pairs of numbers that are digit rotations of each other

0
DatabricksCodingLast asked Aug 2024

A coding interview question asked in Databricks's online assessment, last asked Aug 2024. It tests hash maps and strings.

Two numbers form a cyclic pair when they have the same number of digits and one becomes the other by rotating its digits, moving some leading digits to the end (zero rotations count too). Given an array, count the index pairs i < j whose numbers form a cyclic pair.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • count_cyclic_pairs(a: list[int]) -> int

Example

count_cyclic_pairs([13, 5604, 31, 2, 13, 4560, 546, 654, 456])  ->  5
# 13, 31, 13 give three pairs; 5604-4560; 546-654 (456 is not a rotation of 546)

Constraints

  • The numbers are non-negative integers.

Clarifying questions

  • Are numbers with different digit counts ever a pair (no)?
  • How are leading zeros after a rotation handled: is 5604 → 0456 the number 456? (Compare digit strings, so the length stays 4.)
  • Do equal numbers count as a pair (yes, zero rotations)?

What a strong answer covers

  • A canonical form per number: the smallest rotation of its digit string (O(d^2) for d ≤ 10 digits, or Booth's algorithm).
  • A counter of canonical forms, then sum(c * (c - 1) / 2).
  • O(n × d^2) time, no pairwise comparison.
  • Tests: rotations that start with 0, repeated digits (1111), single digits.

Follow-ups

  • Return the pairs themselves.
  • Count pairs where one is a rotation of the other's reverse.
  • The numbers are very long digit strings.

Where it's asked

What it tests

hash maps · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding