Leetcode 3179: Find the N-th Value After K Seconds

grid47
grid47
Exploring patterns and algorithms
Dec 25, 2023 6 min read

You are given two integers, n and k. Initially, you have an array a of size n, where each element is initialized to 1. After each second, every element in the array is updated to be the sum of all preceding elements plus the element itself. The process repeats for k seconds. You need to return the value of the last element of the array, a[n - 1], after k seconds. Since the result may be very large, return it modulo (10^9 + 7).
Problem
Approach
Steps
Complexity
Input: The input consists of two integers: `n` (the number of elements in the array) and `k` (the number of seconds the array undergoes updates).
Example: Example 1: Input: n = 4, k = 3 Output: 20 Explanation: After 3 seconds, the last element becomes 20.
Constraints:
• 1 <= n, k <= 1000
Output: Return the value of the last element of the array after `k` seconds, modulo (10^9 + 7).
Example: Example 2: Input: n = 5, k = 4 Output: 35 Explanation: After 4 seconds, the last element becomes 35.
Constraints:
• The output will be an integer modulo (10^9 + 7).
Goal: Simulate the update of the array for `k` seconds and compute the value of the last element modulo (10^9 + 7).
Steps:
• Initialize an array `a` of size `n` with all elements set to 1.
• For each second, update each element of the array such that each element becomes the sum of all preceding elements plus the element itself.
• Repeat this for `k` seconds.
• Return the value of the last element modulo (10^9 + 7).
Goal: The input should satisfy the following constraints.
Steps:
• 1 <= n <= 1000
• 1 <= k <= 1000
Assumptions:
• All elements in the array are initially set to 1.
• The number of seconds is limited to 1000, making an iterative approach feasible.
Input: Example 1:
Explanation: For `n = 4` and `k = 3`, the array starts as [1, 1, 1, 1]. After 1 second, the array becomes [1, 2, 3, 4]. After 2 seconds, it becomes [1, 3, 6, 10], and after 3 seconds, it becomes [1, 4, 10, 20]. Therefore, the last element after 3 seconds is 20.

Input: Example 2:
Explanation: For `n = 5` and `k = 4`, the array starts as [1, 1, 1, 1, 1]. After 1 second, the array becomes [1, 2, 3, 4, 5], after 2 seconds it becomes [1, 3, 6, 10, 15], after 3 seconds it becomes [1, 4, 10, 20, 35], and after 4 seconds, the array becomes [1, 5, 15, 35, 70]. Thus, the last element after 4 seconds is 35.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus