Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: A car starts with an empty tank at one of n petrol pumps on a circular route; pump i gives gas[i] and the trip to the next costs cost[i]. Return the start index that completes the circuit, or −1.
Problem: A car starts with an empty tank at one of n petrol pumps on a circular route; pump i gives gas[i] and the trip to the next costs cost[i]. Return the start index that completes the circuit, or −1.
def start(gas, cost):
if sum(gas) < sum(cost): return -1
tank = s = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
s, tank = i + 1, 0
return s
print(start([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]), start([2, 3, 4], [3, 4, 3]))What is printed?- A. 4 -1
- B. 3 0
- C. 0 -1
- D. 3 -1
Correct answer: D. 3 -1
If the total gas covers the total cost, a solution exists, and it is right after the last point where the running tank went negative (no start before that can pass it). Running balance: −2, −4, −6 → reset to start 3; then +3, +6. Second case: total 9 < 10 → −1. O(n), one pass.
More Coding Interview Problems questions
- Problem: Each child must get at least one sweet, and a child with a higher rating than a neighbour must get more than that neighbour. Find…
- Problem: Each position holds the maximum jump length from it. Return the minimum jumps to reach the last index. python def jumps(a): j =…
- Problem: Can you reach the last index if a[i] is the maximum jump from i? java static boolean canReach(int[] a) { int far = 0; for (int i…
- Problem: Coins of denominations {1, 7, 10} are available in unlimited supply. Pay 14 with the fewest coins. What does the greedy 'largest…
- Problem: Split a string into as many parts as possible so each letter appears in at most one part; return the part sizes. python def…
- Problem: Jobs have deadlines and profits; each takes one unit of time. Schedule to maximise profit (greedy by profit, latest free slot)…