C++ 0134.cpp
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int totalgas = 0;
int totalcost = 0;
for (auto x : gas)
totalgas += x;
for (auto x : cost)
totalcost += x;
if (totalgas < totalcost)
return -1;
int tank = 0;
int start = 0;
for (int i = 0; i < gas.size(); i++)
{
if (tank < 0)
{
start = i;
tank = 0;
}
tank += gas[i];
tank -= cost[i];
}
return start;
}
};
Difficulty
and has an acceptance rate of about 48% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Greedy
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “gas station” problem: given two integer arrays gas and cost, it determines the index of a starting station from which a vehicle can complete a full circular tour, or returns -1 when such a tour is impossible. The algorithm proceeds in two distinct phases. The first phase aggregates the total amount of gas and total travel cost to quickly rule out infeasible instances. The second phase scans the stations once, maintaining a running fuel balance and updating a candidate start position whenever the balance becomes negative. The final candidate index is returned as the solution.
Phase 1 - Global feasibility check
The code first computes the sum of all gas supplies and the sum of all travel costs. This is done with two simple loops:
int totalgas = 0;
int totalcost = 0;
for (auto x : gas)
totalgas += x;
for (auto x : cost)
totalcost += x;
If the total gas available across all stations is less than the total cost required to travel the entire circuit, the algorithm immediately returns -1. This early exit handles the edge case where the overall resources are insufficient, regardless of the starting point.
if (totalgas < totalcost)
return -1;
Phase 2 - Determining a viable start station
After confirming that a solution exists in principle, the algorithm initializes two variables: tank, representing the current fuel balance while traversing stations, and start, the candidate starting index.
int tank = 0;
int start = 0;
A single forward loop iterates over each station index i. At each iteration the algorithm first checks whether the current tank value has dropped below zero. A negative balance indicates that any start position up to and including the current index cannot lead to a successful tour, because the vehicle would have run out of fuel before reaching station i. Consequently, the candidate start is moved to the next index, and the fuel balance is reset.
if (tank < 0)
{
start = i;
tank = 0;
}
The fuel balance is then updated by adding the gas obtained at station i and subtracting the cost to travel to the next station.
tank += gas[i];
tank -= cost[i];
Because the loop processes each station exactly once, the final value of start points to the only index that can complete the circuit when the global feasibility condition holds. The method concludes by returning this index.
return start;
Edge-case handling
The algorithm gracefully handles several edge conditions:
- Empty input - When both
gasandcostare empty, the initial sums are zero, the feasibility check passes, and the loop body is never executed. The method returns0, which is a sensible default for an empty circuit. - Single-station circuit - With one station, the feasibility check ensures that
gas[0]is at leastcost[0]. The loop then processes the sole station; if the tank never becomes negative,startremains0, correctly identifying the only possible start. - All stations with equal gas and cost - The total sums are equal, so the algorithm proceeds to the second phase. Since the tank never drops below zero, the initial
startof0is returned, reflecting that any station could serve as a valid start. - Large integer values - The use of
intfor accumulation assumes that the sum of all elements fits within the 32-bit range. Within the problem’s typical constraints, this is acceptable, and the code correctly aggregates the values without overflow checks.
Performance optimizations
The implementation achieves optimal performance through several deliberate choices:
- Early termination - By checking the global feasibility before any per-station processing, the algorithm avoids unnecessary work when the total gas is insufficient, saving time proportional to the size of the input.
- Single pass for start determination - The second phase uses a single linear scan, updating the candidate start only when the running balance becomes negative. This eliminates the need for nested loops or repeated traversals, ensuring that each element is examined exactly once.
- In-place balance tracking - The variable
tankaccumulates the net fuel without allocating auxiliary arrays or data structures. This minimal memory footprint contributes to faster execution and lower cache pressure. - Avoidance of modulo arithmetic - The algorithm does not explicitly simulate the circular nature of the route; instead, it relies on the global feasibility guarantee and the linear scan to infer the correct start. This sidesteps the overhead of modulo operations that would be required in a naïve circular simulation.
Overall, the code delivers a concise, linear-time solution that efficiently resolves the gas-station circuit problem while correctly handling a variety of edge conditions.
ELI5 - Simplified Explanation
Imagine you have a little toy car that needs fuel to drive around a track made of many gas stations. Each station gives the car some fuel, but driving to the next station uses up some of that fuel.
The code first checks to see if there is enough total fuel in the whole world to cover the entire trip. If the total amount of fuel is less than the total amount needed to drive around, the car simply cannot finish the trip no matter where it starts.
If there is enough fuel, the code pretends to start driving from the beginning of the track. It keeps track of how much fuel is in the car as it goes from station to station. If the car ever runs out of fuel before reaching the next stop, it means that the place where the car started was not a good choice. When this happens, the car resets its fuel tank to empty and tries starting fresh from the current station instead. By doing this, it eventually finds the perfect spot on the track where the car can start and successfully make it all the way around the circuit without ever getting stuck.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | Python | C++ | Java | TS | |||||||
| WalkCCC | Python | C++ | Java | |||||||||
| leetcode.ca | Python | C++ | Java | C# | Go | TS | ||||||
| LeetcodeHelp | Python | C++ | Java | |||||||||
| MemoryLimitExceeded | Python | C++ | ||||||||||
| Progiez | Python | C++ | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python, Python | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 2202: Maximize the Topmost Element After K Moves
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality