Data Structures & Algorithms Greedy Algorithms
💡
Exercise 139

Gas Station 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

n gas stations in a circle. gas[i] = fuel at station i, cost[i] = fuel to travel to next station. Find the starting station to complete the circuit, or -1.

Greedy: if total gas >= total cost, solution exists. Track running tank; when it goes negative, next station becomes the new start.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Find the starting gas station index.
If sum(gas) < sum(cost), return -1. Track tank. When tank < 0, reset start to next index and tank to 0.
🧪 Test Cases
Input
canCompleteCircuit([1,2,3,4,5], [3,4,5,1,2])
Expected
3
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.