Sum of K-Digit Numbers in a Range Problem
Description
LeetCode Problem 3855.
You are given three integers l, r, and k.
Consider all possible integers consisting of exactly k digits, where each digit is chosen independently from the integer range [l, r] (inclusive). If 0 is included in the range, leading zeros are allowed.
Return an integer representing the sum of all such numbers. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: l = 1, r = 2, k = 2
Output: 66
Explanation:
- All numbers formed using k = 2 digits in the range [1, 2] are 11, 12, 21, 22.
- The total sum is 11 + 12 + 21 + 22 = 66.
Example 2:
Input: l = 0, r = 1, k = 3
Output: 444
Explanation:
- All numbers formed using k = 3 digits in the range [0, 1] are 000, 001, 010, 011, 100, 101, 110, 111.
- These numbers without leading zeros are 0, 1, 10, 11, 100, 101, 110, 111.
- The total sum is 444.
Example 3:
Input: l = 5, r = 5, k = 10
Output: 555555520
Explanation:
- 5555555555 is the only valid number consisting of k = 10 digits in the range [5, 5].
- The total sum is 5555555555 % (10^9 + 7) = 555555520.
Constraints:
0 <= l <= r <= 91 <= k <= 10^9
Solution
Approach: Math
Each of the k positions can hold any of the n = r - l + 1 digits, so there are n^k numbers. At one position, each digit value appears n^(k-1) times, so the digits at that position add up to (l + r) * n / 2 * n^(k-1).
The positions have weights 1, 10, 100, ..., 10k-1, whose sum is (10^k - 1) / 9. Multiply the two parts, all modulo 109 + 7, using fast exponentiation and the modular inverse of 9 (Fermat's little theorem).
Complexity: O(log k) time and O(1) space.
class Solution:
def sumOfNumbers(self, l: int, r: int, k: int) -> int:
mod = 10**9 + 7
n = r - l + 1
# ((l + r) * (r - l + 1) // 2) % mod
total = (l + r) * n // 2 % mod
# pow(r - l + 1, k - 1, mod)
part1 = pow(n % mod, k - 1, mod)
# (pow(10, k, mod) - 1)
part2 = (pow(10, k, mod) - 1) % mod
# Fermat inverse of 9
inv9 = pow(9, mod - 2, mod)
ans = total
ans = ans * part1 % mod
ans = ans * part2 % mod
ans = ans * inv9 % mod
return ans