Tuesday, July 21, 2015

Gas Station | Leetcode

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.

---

Solution: For each starting point i, check from index i to index n - 1 (where n is the circuit length), and then from 0 to i - 1. At each gas station, fill up the tank and travel to the next gas station, which is tank += gas[i] - cost[i]. If at any point the tank falls to negative (0 is ok), then this starting point i will not work. If we manage to get through the entire circuit with tank >= 0, then i is the answer.

The key step is to avoid an O(N^2) time algorithm and use an O(N) time algorithm. For example, at starting point i=4, we check indexes 4, 5, 6 and 7, and at index=7, the tank falls to negative. There is no need to check for starting points i=5, 6, and 7 again. Thus we can skip from i=4 directly to i=8. Doing this will make sure that we iterate through the circuit only once to get the answer, thus an O(N) algorithm.

If we use an O(N^2) algorithm, it will not pass the Leetcode submission.
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        for (int i = 0; i < gas.length; i++) {
            int tank = 0;
            for (int j = 0, index = i; j < gas.length; j++, index++) {
                if (index == gas.length) index = 0;
                tank += gas[index] - cost[index];
                if (tank < 0) {
                    // Key step: begin next loop from j.
                    if (j > i) i = j;
                    break;
                }
            }
            if (tank >= 0) return i;
        }
        return -1;
    }
}

No comments: