Data Structures & AlgorithmsHardProduct Company SDE · greedy OA
Problem: Each element of [2, 3, 1, 1, 4] is the maximum jump length from that index. What is the minimum number of jumps to reach the last index? Run the greedy code.
Problem: Each element of [2, 3, 1, 1, 4] is the maximum jump length from that index. What is the minimum number of jumps to reach the last index? Run the greedy code.
def jumps(a):
n = len(a)
cnt = 0
cur = far = 0
for i in range(n - 1):
far = max(far, i + a[i])
if i == cur:
cnt += 1
cur = far
return cnt
print(jumps([2, 3, 1, 1, 4]))What is printed?- A. 2
- B. 3
- C. 1
- D. 4
Correct answer: A. 2
Jump from index 0 reaches index 1 or 2; from index 1 (reach 4) one more jump reaches the last index. The greedy keeps the farthest reach in each jump layer.
More Coding Interview Problems questions
- Problem: A circular route has gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2] (cost to travel from station i to i+1). Find the start…
- Problem: What is the minimum number of intervals to remove so that the rest are pairwise non-overlapping (touching at an endpoint is…
- Problem: The prefix sums of [2, 5, 1, 7, 3] are stored in a list p. What is printed by the code, which finds the first index whose prefix…
- Problem: Arrange the numbers 3, 30, 34, 5, 9 so that the concatenation is the largest possible. Run the code and state the printed string…
- Problem: How many integers x with 1 <= x <= 100 satisfy x^3 ≡ x (mod 7)? python print(sum(1 for x in range(1, 101) if pow(x, 3, 7) == x %…
- Problem: What does the following print? python from math import lcm print(lcm(range(1, 11)))