← Home

134. Gas Station

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
134

This is one of those problems where the clean idea matters more than the amount of code. For 134. Gas Station, the solution in this repository is mainly a greedy solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are canCompleteCircuit.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 168 ms, faster than 18.77% of C++ online submissions for Gas Station.
02//Memory Usage: 10 MB, less than 27.31% of C++ online submissions for Gas Station.
03class Solution {
04public:
05    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
06        int n = gas.size();
07        
08        //candidate start point
09        vector<int> cand;
10        
11        for(int i = 0; i < n; ++i){
12            if(gas[i] >= cost[i])
13                cand.push_back(i);
14        }
15        
16        for(int start : cand){
17            bool canreach = true;
18            int cur = 0;
19            for(int i = start; i < start+n; ++i){
20                cur += gas[i%n] - cost[i%n];
21                if(cur < 0){
22                    canreach = false;
23                    break;
24                }
25            }
26            if(canreach){
27                return start;
28            }
29        }
30        
31        return -1;
32    }
33};
34
35//Greedy
36//Runtime: 8 ms, faster than 96.63% of C++ online submissions for Gas Station.
37//Memory Usage: 10 MB, less than 35.07% of C++ online submissions for Gas Station.
38class Solution {
39public:
40    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
41        int n = gas.size();
42        
43        int total = 0;
44        
45        for(int i = 0; i < n; ++i){
46            total += gas[i] - cost[i];
47        }
48        
49        if(total < 0){
50            return -1;
51        }
52        
53        /*
54        If the total number of gas is bigger than 
55        the total number of cost. 
56        There must be a solution.
57        
58        Proof:
59        http://blog.shengwei.li/leetcode-gas-station/
60        - If there is only one gas station, it’s true.
61        - If there are two gas stations a and b, and gas(a) cannot afford cost(a), i.e., gas(a) < cost(a), then gas(b) must be greater than cost(b), i.e., gas(b) > cost(b), since gas(a) + gas(b) > cost(a) + cost(b); so there must be a way too.
62        - If there are three gas stations a, b, and c, where gas(a) < cost(a), i.e., we cannot travel from a to b directly, then:
63        - either if gas(b) < cost(b), i.e., we cannot travel from b to c directly, then gas(c) > cost(c), so we can start at c and travel to a; since gas(b) < cost(b), gas(c) + gas(a) must be greater than cost(c) + cost(a), so we can continue traveling from a to b. **Key Point:** this can be considered as there is one station at c’ with gas(c’) = gas(c) + gas(a) and the cost from c’ to b is cost(c’) = cost(c) + cost(a), and the problem reduces to a problem with two stations. This in turn becomes the problem with two stations above.
64        - or if gas(b) >= cost(b), we can travel from b to c directly. Similar to the case above, this problem can reduce to a problem with two stations b’ and a, where gas(b’) = gas(b) + gas(c) and cost(b’) = cost(b) + cost(c). Since gas(a) < cost(a), gas(b’) must be greater than cost(b’), so it’s solved too.
65        - For problems with more stations, we can reduce them in a similar way. In fact, as seen above for the example of three stations, the problem of two stations can also reduce to the initial problem with one station.
66        */
67        
68        int start = 0, tank = 0;
69        for(int i = 0; i < n; ++i){
70            tank += gas[i] - cost[i];
71            if(tank < 0){
72                /*
73                if A cannot reach B, 
74                then all C btw A and B cannot reach B
75                (A is start, B is i) 
76                so we choose new start as some position after B
77                
78                Proof: 
79                http://blog.shengwei.li/leetcode-gas-station/
80                say there is a point C between A and B -- that is A can reach C but cannot reach B. Since A cannot reach B, the gas collected between A and B is short of the cost. Starting from A, at the time when the car reaches C, it brings in gas >= 0, and the car still cannot reach B. Thus if the car just starts from C, it definitely cannot reach B.
81                */
82                start = i+1;
83                tank = 0;
84            }
85        }
86        
87        return start;
88    }
89};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.