#3855

Sum of K-Digit Numbers in a Range

Hard
MathDivide and ConquerCombinatoricsNumber TheoryCombinatoricsDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(k)
Space
O(1)
O(1)
💡

Intuition

Time O(k)Space O(1)

Use combinatorial mathematics to calculate the contribution of each digit position directly, avoiding the need to generate all combinations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the sum of digits from l to r: sum_digits = (r - l + 1) * (l + r) / 2.
  2. 2Step 2: For each digit position, compute its contribution as: contribution = sum_digits * (10^p) * (r - l + 1)^(k-1).
  3. 3Step 3: Sum contributions for all k positions and return the result modulo 10^9 + 7.
solution.py7 lines
1def sum_k_digit_numbers_optimal(l, r, k):
2    MOD = 10**9 + 7
3    sum_digits = (r - l + 1) * (l + r) // 2 % MOD
4    total_sum = 0
5    for p in range(k):
6        total_sum = (total_sum + sum_digits * pow(10, p, MOD) * pow(r - l + 1, k - 1, MOD)) % MOD
7    return total_sum

Complexity note: This approach computes contributions directly, leading to linear complexity with respect to k, making it efficient.

  • 1Each digit position contributes independently to the total sum.
  • 2Using combinatorial counting avoids generating all combinations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.