




Sponsored
Sponsored
This approach leverages the greedy paradigm. The main idea is to iterate over the stations while keeping track of the total gas and total cost. Additionally, we maintain a running sum (which is the cumulative balance of gas at each station) and a start index. If the running sum ever becomes negative, it implies that the current segment of the journey is infeasible. Thus, we reset the running sum and choose the next station as the candidate for the starting point. Finally, if the total gas is greater than or equal to the total cost, the last chosen candidate is the valid starting point.
Time Complexity: O(n), where n is the number of stations.
Space Complexity: O(1), as extra space used is constant.
1public class GasStation {
2    public static int canCompleteCircuit(int[] gas, int[] cost) {
3        int totalGas = 0, totalCost = 0, start = 0, currentGas = 0;
4        for (int i = 0; i < gas.length; i++) {
5            totalGas += gas[i];
6            totalCost += cost[i];
7            currentGas += gas[i] - cost[i];
8            if (currentGas < 0) {
9                start = i + 1;
10                currentGas = 0;
11            }
12        }
13        return totalGas >= totalCost ? start : -1;
14    }
15
16    public static void main(String[] args) {
17        int[] gas = {1, 2, 3, 4, 5};
18        int[] cost = {3, 4, 5, 1, 2};
19        System.out.println(canCompleteCircuit(gas, cost));
20    }
21}
22The Java code follows the same philosophy as before: calculate the total available gas and cost. During each iteration, track the cumulative gas available in the variable currentGas. If it falls below zero, the journey can't be completed from the current start point. The loop resets the potential start to the next station and proceeds. After completion, a check ensures a valid circuit is possible before returning the starting index.
This approach attempts to simulate the journey starting from each station. For each potential start, check if the car can complete the circuit using the available gas at each station. While this approach may be easier to understand, it is inefficient because it checks each station iteratively, leading to potentially high computational costs for longer arrays. It is not recommended for larger datasets but can be useful for understanding how the journey works preliminarily.
Time Complexity: O(n^2) due to double iteration.
Space Complexity: O(1) as no extra space is utilized.
1
JavaScript implements a naive approach to test each gas station as a potential starting point. The nested loop verifies the possibility to complete the full circuit from each start, breaking early when the journey fails.