Bird
Raised Fist0

Given the following code snippet implementing the optimal greedy solution for the Gas Station problem, what is the output when gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2]?

easy🧾 Code Trace Q3 of Q15
Greedy Algorithms - Gas Station (Circular)
Given the following code snippet implementing the optimal greedy solution for the Gas Station problem, what is the output when gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2]? ```python def canCompleteCircuit(gas, cost): n = len(gas) net = [gas[i] - cost[i] for i in range(n)] if sum(net) < 0: return -1 prefix = [0] * (2 * n + 1) for i in range(2 * n): prefix[i+1] = prefix[i] + net[i % n] for i in range(n): if prefix[i+n] - prefix[i] >= 0: return i return -1 print(canCompleteCircuit(gas, cost)) ```
A3
B0
C-1
D4
Step-by-Step Solution
Solution:
  1. Step 1: Compute net array

    net = [-2, -2, -2, 3, 3], sum(net) = 0 ≥ 0, so proceed.
  2. Step 2: Check prefix sums for valid start

    Check i=3: prefix[3+5]-prefix[3] ≥ 0, meaning starting at index 3 completes circuit.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Output matches known example result [OK]
Quick Trick: Sum net ≥0 and prefix sums identify start index [OK]
Common Mistakes:
MISTAKES
  • Misindexing prefix sums or off-by-one errors
Trap Explanation:
PITFALL
  • Candidates often confuse prefix indices or forget modulo wrap-around.
Interviewer Note:
CONTEXT
  • Tests ability to trace prefix sums and circular indexing
Master "Gas Station (Circular)" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes