




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.
1function canCompleteCircuit(gas, cost) {
2    let totalGas = 0, totalCost = 0;
3    let start = 0, currentGas = 0;
4
5    for (let i = 0; i < gas.length; i++) {
6        totalGas += gas[i];
7        totalCost += cost[i];
8        currentGas += gas[i] - cost[i];
9
10        if (currentGas < 0) {
11            start = i + 1;
12            currentGas = 0;
13        }
14    }
15    return totalGas >= totalCost ? start : -1;
16}
17
18let gas = [1, 2, 3, 4, 5];
19let cost = [3, 4, 5, 1, 2];
20console.log(canCompleteCircuit(gas, cost));
21In JavaScript, the function uses a standard greedy approach. It keeps updating the running sum of gas left in currentGas; if the running sum is negative, it corresponds to a failed attempt, requiring that the start index be moved to the next station. By ensuring that the total gas exceeds the total cost, it guarantees the possibility of completing the circuit.
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
In Java, the brute force solution is similarly executed by checking every gas station as possible starting points. The journey is processed for each start index by accumulating the individual gas difference, stopping early when the tank gas isn't sufficient.