




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.
1#include <vector>
2#include <iostream>
3
4int canCompleteCircuit(std::vector<int>& gas, std::vector<int>& cost) {
5    int totalGas = 0, totalCost = 0, start = 0, currentGas = 0;
6    for (int i = 0; i < gas.size(); i++) {
7        totalGas += gas[i];
8        totalCost += cost[i];
9        currentGas += gas[i] - cost[i];
10        if (currentGas < 0) {
11            start = i + 1;
12            currentGas = 0;
13        }
14    }
15    return totalGas >= totalCost ? start : -1;
16}
17
18int main() {
19    std::vector<int> gas = {1, 2, 3, 4, 5};
20    std::vector<int> cost = {3, 4, 5, 1, 2};
21    int result = canCompleteCircuit(gas, cost);
22    std::cout << result << std::endl;
23    return 0;
24}
25The C++ solution uses similar logic as the C solution. It computes the cumulative gas balance while iterating through the stations. If at any point this balance is negative, it means the current sequence is not a viable solution. We then reset the balance and mark the next station as a new potential start. Finally, it checks if the overall gas is enough to cover all costs 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
The Python solution uses an iterative brute force algorithm to evaluate each possible starting station. It tests whether a full circuit is possible starting from each index. Any failure results in immediate exit from the loop, and the next index is assessed.