Home
Log in
DescriptionSubmissionsSolution
DescriptionSubmissionsSolution
Loading...

Log in to run or submit

gas =
cost =

Codey

Practise coding problems, test your solutions and track your progress.

Explore

  • Problems
  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

© 2026 Codey. Personal learning project.

Solution
Updated: 2026-02-23

Idea

If total gas < total cost, impossible. Otherwise there is a unique valid start (by greedy).

Approach

Scan stations with tank += gas[i]-cost[i]. If tank drops below 0, you cannot start anywhere in the current segment; reset start to i+1 and tank to 0. At end, if total >= 0, return start.

Why it works

A negative prefix tank means any start within that prefix would have even less fuel at the failure point, so all are invalid.

Code
Loading...
Complexity
Time: O(n)
Space: O(1)
Solution
Updated: 2026-02-23

Idea

If total gas < total cost, impossible. Otherwise there is a unique valid start (by greedy).

Approach

Scan stations with tank += gas[i]-cost[i]. If tank drops below 0, you cannot start anywhere in the current segment; reset start to i+1 and tank to 0. At end, if total >= 0, return start.

Why it works

A negative prefix tank means any start within that prefix would have even less fuel at the failure point, so all are invalid.

Code
Loading...
Complexity
Time: O(n)
Space: O(1)