Gas Station - Problem
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.
If there exists a solution, it is guaranteed to be unique.
Input & Output
Example 1 — Basic Case
$
Input:
gas = [1,2,3,4,5], cost = [3,4,5,1,2]
›
Output:
3
💡 Note:
Starting from station 3: gas=4, cost=1, remaining=3. Continue to station 4: gas=5, cost=2, total=6. Then stations 0,1,2 can be completed with this surplus.
Example 2 — Impossible Case
$
Input:
gas = [2,3,4], cost = [3,4,3]
›
Output:
-1
💡 Note:
Total gas = 9, total cost = 10. Since total cost exceeds total gas, it's impossible to complete the circuit.
Example 3 — Start from Beginning
$
Input:
gas = [5,1,2,3,4], cost = [4,4,1,5,1]
›
Output:
4
💡 Note:
Starting from station 4 works: 4-1=3, then 5-4=4, total=7, enough to complete the rest of the circuit.
Constraints
- 1 ≤ gas.length == cost.length ≤ 104
- 0 ≤ gas[i], cost[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular route with gas amounts and travel costs
2
Process
Find starting point that allows complete circuit
3
Output
Index of valid starting station or -1
Key Takeaway
🎯 Key Insight: Use greedy approach - when tank goes negative, reset start to next station
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code