1458. Balanced Ticket Count

Hard7.5 points estimatedCombinatoricsMaths

A transit company prints tickets whose serial number has exactly 2 * n decimal digits, and leading zeros are allowed. A ticket is called balanced when the sum of its first n digits equals the sum of its last n digits. Marketing wants to know how many balanced serial numbers exist for a given n. Return that count modulo 1000000007. Listing the tickets is hopeless for large n: flipping every digit d of the second half to 9 - d turns the task into counting digit strings with a fixed total, which inclusion-exclusion and precomputed factorials solve in O(n) time and O(n) space.

Example 1

Input:
n = 1
Output:
10
Explanation:

With two digits, the ticket is balanced exactly when both digits are equal, giving 10 tickets.

Example 2

Input:
n = 2
Output:
670
Explanation:

For four-digit tickets there are 670 ways to match the sums of the two halves.

Constraints

1 ≤ n ≤ 105

The result is taken modulo 109 + 7.

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

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…