Data Structures & AlgorithmsVery hardProduct Company SDE · greedy round
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 station index from which a full loop is possible, by running this code.
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 station index from which a full loop is possible, by running this code.
def start(gas, cost):
tot = cur = s = 0
for i in range(len(gas)):
d = gas[i] - cost[i]
tot += d
cur += d
if cur < 0:
s = i + 1
cur = 0
return s if tot >= 0 else -1
print(start([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]))What is printed?- A. 0
- B. 3
- C. 4
- D. 2
Correct answer: B. 3
Stations 0, 1, 2 leave the running fuel negative, so the start moves to station 3, where the cumulative fuel never drops below zero. The total gas equals the total cost, so the loop is feasible from that start.
More Coding Interview Problems questions
- 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)))
- Problem: How many integers from 1 to 100 have exactly 3 positive divisors? python print(sum(1 for x in range(1, 101) if sum(1 for d in…