Magicsheet logo

Find the N-th Value After K Seconds

Medium
75%
Updated 8/1/2025

Find the N-th Value After K Seconds

What is this problem about?

In the Find the N-th Value After K Seconds coding problem, you have an array of nn elements, all initially 1. Every second, each element a[i]a[i] is updated to be the sum of all elements from a[0]a[0] to a[i]a[i] from the previous second. You need to return the value of the nn-th element after kk seconds, modulo 109+710^9 + 7.

Why is this asked in interviews?

Walmart Labs uses this to test whether you can move from Simulation to Combinatorics. While you can simulate the process in O(NimesK)O(N imes K), if NN and KK are large, you need a mathematical solution. This problem is an application of Pascal's Triangle properties and Stars and Bars. It evaluations your ability to recognize that the ii-th element after jj seconds is a binomial coefficient.

Algorithmic pattern used

There are two ways to solve this:

  1. Simulation (O(NimesK)O(N imes K)): Maintain a prefix sum array and update it kk times.
  2. Combinatorics (O(N+K)O(N + K)): The updates describe a process where the jj-th element in the ii-th row of Pascal's triangle is being calculated. Specifically, the nn-th value after kk seconds corresponds to the binomial coefficient (n+k1k)\binom{n+k-1}{k}.

Example explanation

n=3,k=2n = 3, k = 2

  1. Initial: [1, 1, 1]
  2. Sec 1: [1, 1+1, 1+1+1] o o [1, 2, 3]
  3. Sec 2: [1, 1+2, 1+2+3] o o [1, 3, 6] Result: 6. Using formula: (3+212)=(42)=4imes32=6\binom{3+2-1}{2} = \binom{4}{2} = \frac{4 imes 3}{2} = 6.

Common mistakes candidates make

  • Modulo arithmetic: Forgetting to take the modulo at each addition in the simulation.
  • Combinatorial overflow: Not using modular inverse for the division when calculating combinations with large factorials.
  • Complexity: Attempting O(NimesK)O(N imes K) when the problem constraints require O(N+K)O(N+K).

Interview preparation tip

Problems involving "running sums of running sums" are almost always related to Binomial Coefficients or the diagonals of Pascal's Triangle. If you see this pattern, try to map the steps to the (n+k1k)\binom{n+k-1}{k} formula.

Similar Questions