Gas Station Problem

viaGlassdoor

Problem: There are N gas stations along a circular route. Gas station i has gas[i] amount of fuel, and it costs cost[i] fuel to travel from station i to station i+1. Determine the starting gas station index from which you can travel around the entire circuit once, or return -1 if not possible.

Constraints: If a solution exists, it is guaranteed to be unique. Circular route (after the last station, you return to the first).

Example: gas = [1,2,3,4,5], cost = [3,4,5,1,2] -> starting index 3 allows completing the full circuit.

Approach: If total gas >= total cost, a solution exists. Track a running tank balance while iterating; whenever the tank goes negative at station i, reset the candidate start to i+1 and reset the tank to 0 (all stations from the old start up to i cannot be valid starts either). The final candidate start after one pass is the answer. O(n) time, O(1) space.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account