Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7.
Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7.
static long ways3(int n) {
long MOD = 1_000_000_007L;
long[] dp = new long[Math.max(n + 1, 3)];
dp[0] = 1; dp[1] = 1; dp[2] = 2;
for (int i = 3; i <= n; i++)
dp[i] = (dp[i-1] + dp[i-2] + dp[i-3]) % MOD;
return dp[n];
}
// ways3(5) + " " + ways3(10) + " " + ways3(0)What does the commented expression evaluate to?- A. 13 274 0
- B. 13 274 1
- C. 8 274 1
- D. 13 149 1
Correct answer: B. 13 274 1
Tribonacci: 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274. The array is sized at least 3 so dp[2] exists even for n = 0, and dp[0] = 1 (one way: do nothing). O(n).
More Coding Interview Problems questions
- Problem: A frog jumps from stone 0 to stone n − 1; jumping from i to j (j ≤ i + k) costs |h[i] − h[j]|. Find the minimum cost. python def…
- Problem: Count palindromic substrings (each occurrence counts separately). python def countpal(s): n, c = len(s), 0 for center in range(2…
- Problem: Find the length of the longest arithmetic subsequence. python def longestap(a): dp = [{} for in a]; best = 1 for i in…
- Problem: Length of the longest strictly increasing subsequence with the O(n²) DP. cpp int lis(vector<int>& a) { vector<int> dp(a.size()…
- Problem: A hash table keyed by short strings uses Java's String.hashCode. Why do some keys collide? java // String.hashCode: h = 31h + c…
- Problem: Binary search on large indices in C++ (int is 32-bit). cpp int lo = 2000000000, hi = 2100000000; int bad = (lo + hi) / 2; //…