Problem 134

Abstract / Summary

Find the starting gas station index from where a car can complete a circuit given gas and cost arrays.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
28 lines | 646 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 gas and cost are empty, the initial sums are zero, the feasibility check passes, and the loop body is never executed. The method returns 0, which is a sensible default for an empty circuit.
  • Single-station circuit - With one station, the feasibility check ensures that gas[0] is at least cost[0]. The loop then processes the sole station; if the tank never becomes negative, start remains 0, 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 start of 0 is returned, reflecting that any station could serve as a valid start.
  • Large integer values - The use of int for 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 tank accumulates 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.78 | σ = 0.96

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
56 links | 41 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Gas Station - Greedy - Leetcode 134 - Python'
NeetCode 16 mins
Gas Station - Greedy - Leetcode 134 - Python
YouTube video 'L82. Gas Station | Greedy Approach | Leetcode 134'
Shradha Khapra 23 mins
L82. Gas Station | Greedy Approach | Leetcode 134
YouTube video 'Gas Station | LeetCode 134 | C++, Java, Python'
Knowledge Center 24 mins
Gas Station | LeetCode 134 | C++, Java, Python
YouTube video 'Gas Station | Leetcode 134 | Detailed Explanation | Google | Amazon | codestorywithMIK'
codestorywithMIK 47 mins
Gas Station | Leetcode 134 | Detailed Explanation | Google | Amazon | codestorywithMIK
YouTube video 'Gas Station | Leetcode 134 | Greedy'
Ayushi Sharma 15 mins
Gas Station | Leetcode 134 | Greedy
YouTube video 'Gas Station | Live Coding with Explanation | Leetcode - 134'
Algorithms Made Easy 14 mins
Gas Station | Live Coding with Explanation | Leetcode - 134
YouTube video 'gas station | gas station leetcode ⛽🚘| leetcode 134 | gas station september | greedy | two solution'
Naresh Gupta 11 mins
gas station | gas station leetcode ⛽🚘| leetcode 134 | gas station september | greedy | two solution
YouTube video 'Gas Station (LeetCode 134) | Full Solution with Diagrams and animation | Greedy Approach'
Nikhil Lohia 21 mins
Gas Station (LeetCode 134) | Full Solution with Diagrams and animation | Greedy Approach
YouTube video 'Gas Station | Leetcode 134 |Live coding session 🔥🔥🔥🔥 | Linear O(n) Easy Peasy'
Coding Decoded 13 mins
Gas Station | Leetcode 134 |Live coding session 🔥🔥🔥🔥 | Linear O(n) Easy Peasy
YouTube video 'Gas Station - LeetCode 134 - Coding Interview Questions'
One Code Man 4 mins
Gas Station - LeetCode 134 - Coding Interview Questions
YouTube video 'LeetCode 134 | Gas Station Problem Visually Explained | Top Interview 150'
ByteQuest 10 mins
LeetCode 134 | Gas Station Problem Visually Explained | Top Interview 150
YouTube video 'Gas Station | Leet code 134 | Theory explained + Python code'
Sai Anish Malla 15 mins
Gas Station | Leet code 134 | Theory explained + Python code
YouTube video '134. Gas Station | Leetcode | Medium | Java | Kadane's Algorithm | Leetcode Top Interview 150'
AlgorithmHQ 13 mins
134. Gas Station | Leetcode | Medium | Java | Kadane's Algorithm | Leetcode Top Interview 150
YouTube video 'GAS STATION | LEETCODE # 134 | PYTHON | AMAZON & MICROSOFT INTERVIEW QUESTION'
Cracking FAANG 16 mins
GAS STATION | LEETCODE # 134 | PYTHON | AMAZON & MICROSOFT INTERVIEW QUESTION
YouTube video '134. Gas Station | JavaScript | Two Pointers | LeetCode Daily Challenge | Detailed Explanation'
LeetCodeWithMonu 16 mins
134. Gas Station | JavaScript | Two Pointers | LeetCode Daily Challenge | Detailed Explanation
YouTube video '134. Gas Station || Leetcode || Coding with Explanation'
TechWithSaumya 12 mins
134. Gas Station || Leetcode || Coding with Explanation
YouTube video 'Daily Leetcode #1012: Jan 07, 2023 - 134. Gas Station'
Programming Live with Larry 10 mins
Daily Leetcode #1012: Jan 07, 2023 - 134. Gas Station
YouTube video 'LeetCode 134. Gas Station'
Happy Coding 16 mins
LeetCode 134. Gas Station
YouTube video 'Google Coding Interview Question | Leetcode 134 | Gas Station'
WorkWithGoogler 8 mins
Google Coding Interview Question | Leetcode 134 | Gas Station
YouTube video '134 || Gas Station || Leetcode Daily Challenge'
CodeFreaks 14 mins
134 || Gas Station || Leetcode Daily Challenge
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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