Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
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.
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.
def frog(h, k):
n = len(h); dp = [0] + [float('inf')] * (n - 1)
for i in range(1, n):
for j in range(max(0, i - k), i):
dp[i] = min(dp[i], dp[j] + abs(h[i] - h[j]))
return dp[-1]
print(frog([10, 30, 40, 50, 20], 3), frog([10, 20, 10], 1))What is printed?- A. 40 20
- B. 30 0
- C. 20 20
- D. 30 20
Correct answer: D. 30 20
dp[i] = min over the last k stones of dp[j] + |h[i] − h[j]|. With k = 3: 10 → 20 directly is not allowed (4 stones away), but 10 → 30 (20) → 20 (10) = 30. With k = 1 every stone is visited: 10 + 10 = 20. O(n·k).
More Coding Interview Problems questions
- 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; //…
- Problem: Find the celebrity (known by all, knows nobody) with O(n) calls to knows(a, b). python M = [[0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0…