Sum of Increasing Product Blocks Problem
#3792
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3792.
You are given an integer n.
A sequence is formed as follows:
- The
1^stblock contains1. - The
2^ndblock contains2 * 3. - The
i^thblock is the product of the nexticonsecutive integers.
Let F(n) be the sum of the first n blocks.
Return an integer denoting F(n) modulo 10^9 + 7.
Example 1:
Input: n = 3
Output: 127
Explanation:
- Block 1: 1
- Block 2: 2 * 3 = 6
- Block 3: 4 * 5 * 6 = 120
F(3) = 1 + 6 + 120 = 127
Example 2:
Input: n = 7
Output: 6997165
Explanation:
- Block 1: 1
- Block 2: 2 * 3 = 6
- Block 3: 4 * 5 * 6 = 120
- Block 4: 7 * 8 * 9 * 10 = 5040
- Block 5: 11 * 12 * 13 * 14 * 15 = 360360
- Block 6: 16 * 17 * 18 * 19 * 20 * 21 = 39070080
- Block 7: 22 * 23 * 24 * 25 * 26 * 27 * 28 = 5967561600
F(7) = 6006997207 % (10^9 + 7) = 6997165
Constraints:
1 <= n <= 1000
Solution
Approach: Simulation
Block i starts right after block i - 1 ends, so we keep k, the first integer of the current block, and move it forward by i after each block. For every block we multiply its i consecutive integers, taking the remainder modulo 109 + 7 after each multiplication so the numbers stay small, and add the result to the answer (also modulo 109 + 7).
There are n blocks with at most n numbers each, which is fast enough for n <= 1000.
Complexity: O(n2) time and O(1) extra space.
class Solution:
def sumOfBlocks(self, n: int) -> int:
ans = 0
mod = 10**9 + 7
k = 1
for i in range(1, n + 1):
x = 1
for j in range(k, k + i):
x = (x * j) % mod
ans = (ans + x) % mod
k += i
return ans