134. Gas Station | LeetCode | Top Interview 150 | Coding Questions

Published: (December 17, 2025 at 05:06 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

https://leetcode.com/problems/gas-station/

leetcode 134

Solution

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int totalGas = 0;
        int totalCost = 0;

        for (int i = 0; i < gas.length; i++) {
            totalGas += gas[i];
            totalCost += cost[i];
        }

        if (totalGas < totalCost) {
            return -1;
        }

        int currGas = 0;
        int startIndex = 0;

        for (int i = 0; i < gas.length; i++) {
            currGas += gas[i] - cost[i];

            if (currGas < 0) {
                startIndex = i + 1;
                currGas = 0;
            }
        }

        return startIndex;
    }
}
Back to Blog

Related posts

Read more »