1258. Glued Number Multiples

A lottery clerk glues two ticket numbers into one long number by writing the first in decimal and the second right after it, so 12 and 345 become 12345. Given the array nums and an integer k, return the number of index pairs i < j for which the number made by nums[i] followed by nums[j] is divisible by k. Pairs are counted by position, so equal values at different positions count separately.

The glued number equals nums[i] * 10^len(nums[j]) + nums[j], where len is the digit count, and it can have 20 digits, so work with remainders modulo k and 64-bit arithmetic. Aim for O(10n) expected time and O(10n) space using one hash map per digit length, then return the count as a long.

Example 1

Input:
nums = [47,8,310,95,1204,6,73], k = 7
Output:
3
Explanation:

Among all ordered pairs i < j, exactly 3 glued numbers are divisible by 7.

Example 2

Input:
nums = [250,16,75,4,900,32,500], k = 25
Output:
12
Explanation:

With k = 25 a glued number qualifies when it ends in 00, 25, 50 or 75, and 12 pairs do.

Example 3

Input:
nums = [19,64,230,8,57,11], k = 6
Output:
4
Explanation:

With k = 6 a glued number must be even with a digit sum divisible by 3, and 4 pairs qualify.

Constraints

1 ≤ n ≤ 1000 where n = nums.length; 1 ≤ nums[i] ≤ 109; 2 ≤ k ≤ 106.

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(10n)
Space
O(10n)

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…