Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 134] Gas Station

Question

link

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note:
The solution is guaranteed to be unique.

Stats

Adjusted Difficulty 4
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is a tough question, which requires a lot of math-related thinking.

My solution is IMHO very simple and easy. I first do a cumulation of gas from beginning to the end, and find the lowest cumulative value of the gas tank (of course can be negative). That point is where I start the journey, which is to say, I will validate the path from that point, and then return the result.

This idea is not seen on Internet, although it is just 2 loops thru the list, and time complexity is also O(n). Anyway, there’s a great solution which most people uses.

There’s a great post that gives 2 valid conclusions:

  1. If car starts at A and can not reach B (let’s say B is the first station that A can not reach), then any station between A and B can not reach B.
  2. If the total number of gas is bigger than the total number of cost. There must be a valid solution.

From here, a great solution can be found.

Solution

A very detailed explanation and code is found from this blog.

  1. 从i开始,j是当前station的指针,sum += gas[j] – cost[j] (从j站加了油,再算上从i开始走到j剩的油,走到j+1站还能剩下多少油)
  2. 如果sum < 0,说明从i开始是不行的。那能不能从i..j中间的某个位置开始呢?假设能从k (i <=k<=j)走,那么i..j < 0,若k..j >=0,说明i..k – 1更是<0,那从k处就早该断开了,根本轮不到j。
  3. 所以一旦sum<0,i就赋成j + 1,sum归零。

And note that if i is moved to j, there is no need to check (0..old_i) again, because this range must be reachable (write code again for beter understanding).

Coding this solution is not easy! I failed to do it.

Code

First, my solution

public int canCompleteCircuit(int[] gas, int[] cost) {
    int len = gas.length;
    if (len == 0) return -1;
    int start = -1, min = Integer.MAX_VALUE, total = 0;
    for (int i = 0; i < len; i ++) {
        total += getDiff(gas, cost, i);
        if (total < min) {
            min = total;
            start = i;
        }
    }
    start = (start + 1) % len;
    // now traverse the route from start 
    total = 0;
    for (int i = 0; i < len; i ++) {
        total += getDiff(gas, cost, (start + i) % len);
        if (total < 0) return -1; 
    }
    return start;
}

private int getDiff(int[] gas, int[] cost, int i) {
    return gas[i] - cost[i];
}

Second, best solution

public int canCompleteCircuit(int[] gas, int[] cost) {
    int i = 0, j = 0;
    int sum = 0;
    int total = 0;
    while (j < gas.length) {
        int diff = gas[j] - cost[j];
        if (sum + diff < 0) {
            i = j + 1;
            sum = 0;
        } else {
            sum += diff;
        }
        j++;
        total += diff;
    }
    return total >= 0 ? i : -1;
}