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
Find N-th Value After K SecondsInitial (k=0):1111SimulateAfter 1 second:1234After 2 seconds:13610a[1] = a[0] + a[1] = 1 + 1 = 2a[2] = a[0] + a[1] + a[2] = 1 + 1 + 1 = 3a[3] = a[0] + a[1] + a[2] + a[3] = 1 + 1 + 1 + 1 = 4a[1] = 1 + 2 = 3a[2] = 1 + 3 = 4... wait, that\'s wrongActually: a[2] = 1 + 2 + 3 = 6a[3] = 1 + 3 + 6 = 10Output: a[n-1] = 10
Understanding the Visualization
1
Input
Array of n ones, simulate for k seconds
2
Process
Each second: element = sum of all left elements + itself
3
Output
Return last element after k seconds
Key Takeaway
🎯 Key Insight: The pattern follows Pascal's triangle - use mathematical formula for optimal O(n) 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