Skip to content

Interview Solver

FeaturesPricingHelp
Sign In
FeaturesPricingHelpSign In
  1. Interview Questions
  2. /
  3. Problems
  4. /
  5. Gas Station

Gas Station

Find the station where you can start a loop around a circular route without running out of fuel. A one-pass greedy that restarts whenever the tank goes negative. Solve it below in Python or JavaScript, then read the walkthrough.

MediumArrayGreedyAsked at 123 companies incl. Google, Amazon, Meta

Problem

There are n fuel stations on a circular road, numbered 0 to n - 1. At station i you can pick up gas[i] units of fuel, and driving from station i to the next station (i + 1, or back to 0 from the last one) burns cost[i] units.

Your car's tank has no size limit, and it starts empty. You begin at one station, take its fuel, and drive clockwise. Return the index of a starting station from which you can drive all the way around and return to it without the tank ever going below zero, or -1 if no such station exists.

When a valid starting station exists, the inputs guarantee it is the only one.

Example 1

Input
gas = [1, 6, 2, 3], cost = [4, 1, 3, 2]
Output
1

Starting at 1, the tank holds 6 − 1 = 5 on arrival at 2, then 5 + 2 − 3 = 4 at 3, then 4 + 3 − 2 = 5 at 0, then 5 + 1 − 4 = 2 back at 1.

Example 2

Input
gas = [3, 3, 3], cost = [4, 4, 2]
Output
-1

There are 9 units of fuel in total but the loop costs 10.

Constraints

  • 1 ≤ n ≤ 10⁵
  • gas.length == cost.length == n
  • 0 ≤ gas[i], cost[i] ≤ 10⁴
  • If a valid start exists, it is unique.

Practice

1
2
3
4

Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.

Get asked Gas Station in a real interview?

Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.

Start Free Trial

How to solve Gas Station

Pattern: Greedy restart on deficit

Look at the net change at each station, diff[i] = gas[i] - cost[i]. Two facts do all the work.

First, the total decides whether any answer exists. If sum(diff) < 0, the loop burns more fuel than there is, so no start works. If it's ≥ 0, some start does.

Second, a failure rules out a whole stretch of starts. Say you start at s and the tank first goes negative after leaving station j. Every station between s and j was reached with a tank of at least zero, so starting at any of them means arriving at j with less fuel than you had, and you'd fail at j too. So you can skip straight to j + 1 as the next candidate. Each station is visited once, and the last candidate standing is the answer.

Approach 1: Simulate from every start

For each station, drive around the loop tracking the tank and stop at the first negative value. Return the first start that makes it all the way. Clear, but up to n steps for each of n starts.

Time O(n²) · Space O(1)

Approach 2: One pass with a running tank

  1. Keep total (sum of every diff), tank (fuel since the current candidate) and start = 0.
  2. For each i: add diff[i] to both total and tank. If tank < 0, set start = i + 1 and tank = 0.
  3. Return start if total >= 0, otherwise -1.

You never need to wrap around to verify start: the tank stayed non-negative from start to the end, and the total being non-negative covers the part from 0 back to start.

Time O(n) · Space O(1)

ApproachTimeSpace
Simulate from every startO(n²)O(1)
One pass with a running tankO(n)O(1)

Solution code

Try the practice editor first. Both solutions pass every test above.

▸Gas Station solution in Python
def can_complete_circuit(gas: list[int], cost: list[int]) -> int:
    total = 0
    tank = 0
    start = 0
    for i in range(len(gas)):
        diff = gas[i] - cost[i]
        total += diff
        tank += diff
        if tank < 0:
            start = i + 1
            tank = 0
    return start if total >= 0 else -1
▸Gas Station solution in JavaScript
function canCompleteCircuit(gas, cost) {
  let total = 0;
  let tank = 0;
  let start = 0;
  for (let i = 0; i < gas.length; i++) {
    const diff = gas[i] - cost[i];
    total += diff;
    tank += diff;
    if (tank < 0) {
      start = i + 1;
      tank = 0;
    }
  }
  return total >= 0 ? start : -1;
}

Common mistakes

  • Returning `start` without checking the total, which gives a station even when the trip is impossible.
  • Restarting at `start + 1` after a failure instead of `i + 1`, which is correct but quietly brings back the O(n²) cost.
  • Resetting the tank to the current station's gas rather than to zero.
  • Simulating a second lap to verify the answer, which is unnecessary once the total is non-negative.

What interviewers look for

The one-pass code is short; the interviewer cares about the two justifications. Say them as claims: "if the total is non-negative a solution exists" and "if I fail at j, nothing between my start and j can work either." Then prove the second in a sentence: each of those stations was reached with a non-negative tank, so starting there only removes fuel.

Start from the O(n²) simulation and point out the wasted work, a failed start that you then retry from its next station, before introducing the skip. It shows the optimization comes from reasoning about the simulation, not from a remembered trick.

Follow-up questions

Why does a non-negative total guarantee a valid start?

Take the prefix sums of diff and pick the index right after the lowest prefix sum. Starting there, every partial sum is measured from the minimum, so it can never go below zero, and the full loop ends at total ≥ 0.

What if several starts can work and you need all of them?

A start s is valid exactly when the prefix sum just before s equals the global minimum prefix sum (and the total is non-negative). Compute prefix sums once and collect every index that follows a minimum.

What if you may also drive counterclockwise?

Run the same pass a second time on the reversed route. Going counterclockwise from station i to i − 1 burns cost[i − 1], so the net change at i is gas[i] − cost[i − 1] (wrapping at 0). The total is the same in both directions, so the check for −1 does not change.

Companies that ask Gas Station

Gas Station is tagged by 123 companies in our interview dataset. The score shows how often it comes up at each company.

  • Latitude Ai100%
  • Cme Group100%
  • Scale Ai100%
  • Bitgo96.8%
  • Skyworks Solutions96%
  • Goat Group95%
  • Stockx95%
  • Loom94%
  • Guardant Health93%
  • Quantcast93%
  • Vistaprint87%
  • Vaxcyte86%
  • Airtasker86%
  • Renesas Electronics84%
  • Apptronik83%
  • Dxc Technology82%
  • Zego81%
  • Retailmenot80%
  • Fireeye79%
  • Alation79%
  • Nasa Jpl79%
  • Elsevier78%
  • Fdm Group78%
  • Sprinklr77.6%

and 99 more.

Practice next

  • Container With Most WaterMediumTwo pointers from both ends
  • Two SumEasyHash map of complements
  • Number of IslandsMediumFlood fill (DFS/BFS on a grid)
  • Merge IntervalsMediumSort, then sweep

Get live help in the real interview

Working solutions in real time during your actual interview. Invisible to screensharing.

Start Free Trial

No credit card required

Interview Solver
  • Home
  • About
  • Pricing
  • Sign in
  • Contact
  • Blog
  • Companion
  • Mobile
  • Help Center
  • Developers
  • Use Cases
  • Software Engineer
  • Product Manager
  • Misc
  • Privacy Policy
  • Terms and Conditions
  • Refund & Cancellation
  • Discord Community
  • Affiliate Program
  • Compare
  • All Comparisons
  • vs Final Round AI
  • vs UltraCode
  • vs Interview Coder
  • vs LockedIn AI
  • vs AI Apply
  • Free Tools
  • ATS Resume Checker
  • STAR Method Builder
  • Salary Lookup
  • Big O Cheat Sheet
  • Total Comp Calculator
  • View All →
  • Interview Questions
  • Google Questions
  • Amazon Questions
  • Microsoft Questions
  • Meta Questions
  • Apple Questions
  • TikTok Questions
  • View All →
© 2026 Interview Solver, Inc. All rights reserved.