Find the N-th Value After K Seconds - Problem

You are given two integers n and k. Initially, you start with an array a of n integers where a[i] = 1 for all 0 <= i <= n - 1.

After each second, you simultaneously update each element to be the sum of all its preceding elements plus the element itself. For example, after one second, a[0] remains the same, a[1] becomes a[0] + a[1], a[2] becomes a[0] + a[1] + a[2], and so on.

Return the value of a[n - 1] after k seconds. Since the answer may be very large, return it modulo 10^9 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, k = 2
Output: 10
💡 Note: Initial: [1,1,1,1]. After 1s: [1,2,3,4]. After 2s: [1,3,6,10]. Return a[3] = 10.
Example 2 — Single Element
$ Input: n = 1, k = 3
Output: 1
💡 Note: Array has only one element [1], which never changes regardless of k.
Example 3 — No Time Elapsed
$ Input: n = 3, k = 0
Output: 1
💡 Note: No seconds pass, so array remains [1,1,1]. Return a[2] = 1.

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ k ≤ 1000

Visualization

Tap to expand
N-th Value After K Seconds INPUT Initial Array (k=0): 1 a[0] 1 a[1] 1 a[2] 1 a[3] Input Parameters: n = 4 k = 2 Each second: a[i] = sum(a[0..i]) After k=1: 1 2 3 4 After k=2: 1 3 6 10 ALGORITHM STEPS 1 Recognize Pattern Values form Pascal's Triangle 2 Use Combination a[n-1] = C(n+k-2, k) 3 Calculate C(n+k-2, k) C(4+2-2, 2) = C(4, 2) 4 Apply Modulo Result mod 10^9 + 7 Computation: C(4,2) = 4! / (2! * 2!) = 24 / (2 * 2) = 24 / 4 = 10 Time: O(n+k) | Space: O(1) FINAL RESULT Array after k=2 seconds: 1 3 6 10 Output: 10 OK - Verified a[n-1] = a[3] = 10 C(4,2) = 10 10 mod (10^9+7) = 10 Key Insight: The prefix sum operation creates values that correspond to binomial coefficients (Pascal's Triangle). After k seconds, a[n-1] equals C(n+k-2, k) = C(n+k-2, n-2). This allows O(n+k) solution using modular inverse for factorial division, avoiding the exponential time of simulation. TutorialsPoint - Find the N-th Value After K Seconds | Optimal Solution
Asked in
Google 25 Microsoft 20 Amazon 15
21.3K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen