#3179
Find the N-th Value After K Seconds
MediumArrayMathSimulationCombinatoricsPrefix SumPrefix SumDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * k) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * k)Space O(n)
Instead of simulating each second, we can recognize that the problem can be solved using combinatorial mathematics. The value at a[n-1] after k seconds corresponds to the number of ways to select elements from the previous states.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a 2D array 'dp' where dp[i][j] represents the value at index j after i seconds.
- 2Step 2: Set dp[0][j] = 1 for all j from 0 to n-1 (initial state).
- 3Step 3: For each second from 1 to k, compute each dp[i][j] as the sum of all dp[i-1][m] for m from 0 to j.
- 4Step 4: Return dp[k][n - 1] modulo 10^9 + 7.
solution.py15 lines
1# Full working Python code
2
3def find_nth_value_optimal(n, k):
4 MOD = 10**9 + 7
5 dp = [[0] * n for _ in range(k + 1)]
6 for j in range(n):
7 dp[0][j] = 1
8 for i in range(1, k + 1):
9 for j in range(n):
10 dp[i][j] = dp[i][j - 1] if j > 0 else 0
11 dp[i][j] = (dp[i][j] + dp[i - 1][j]) % MOD
12 return dp[k][n - 1]
13
14# Example usage
15print(find_nth_value_optimal(4, 5)) # Output: 56ℹ
Complexity note: This complexity arises because we fill a 2D array of size (k+1) x n, and for each second, we iterate through n elements.
- 1The problem can be viewed as a prefix sum problem.
- 2The final value can be derived from combinatorial principles.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.