DevPath

← All problems

Gas Station

Medium greedy · arrays

Description

Given gas and cost per station in a circle, return the starting index from which you can complete the circuit, or -1. A unique answer is guaranteed when one exists.

Constraints

1 <= n <= 100000

Examples

Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]

Output: 3

Hints (1)
  • If total gas is less than total cost there is no answer; otherwise reset the start when the tank goes negative.

Solutions

Single pass with reset. · Time O(n) · Space O(1)

func canCompleteCircuit(gas, cost []int) int {
    total, tank, start := 0, 0, 0
    for i := range gas {
        diff := gas[i] - cost[i]
        total += diff
        tank += diff
        if tank < 0 {
            start = i + 1
            tank = 0
        }
    }
    if total >= 0 {
        return start
    }
    return -1
}

Create a free account to submit solutions, track progress and save problems.

Create account