Bird
Raised Fist0

What is the output when gas = [5] and cost = [4]?

medium🧾 Code Trace Q4 of Q15
Greedy Algorithms - Gas Station (Circular)
Consider the optimal greedy solution for the Gas Station problem. What is the output when gas = [5] and cost = [4]? ```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)) ```
A0
B1
C-1
DIndexError
Step-by-Step Solution
Solution:
  1. Step 1: Compute net array

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

    prefix sums allow start at index 0 since prefix[0+1]-prefix[0] = 1 ≥ 0.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Single station with surplus gas returns 0 [OK]
Quick Trick: Single element with gas ≥ cost -> start at 0 [OK]
Common Mistakes:
MISTAKES
  • Assuming no solution for single element with surplus
Trap Explanation:
PITFALL
  • Candidates may expect errors or -1 for single-element edge cases.
Interviewer Note:
CONTEXT
  • Tests handling of minimal input edge cases
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