Gas Station Circular Tour
Updated
Problem statement
There are n petrol pumps on a circular route, numbered 0 through n - 1. Pump i gives gas[i] litres of fuel. Driving from it to the next pump uses cost[i] litres. Your truck starts with an empty tank that has no size limit, and it picks up the fuel at every pump it visits.
Find a starting pump from which the truck can drive one full clockwise circuit without its tank going negative. Fuel may reach exactly zero. Return the smallest such pump index, or -1 if no starting pump works.
Function
gasStation(gas: int[], cost: int[]) → intExamples
Example 1
gas = [1,2,3,4,5]cost = [3,4,5,1,2]return = 3The first three pumps each give less fuel than the drive to the next pump, so a start at any of them fails right away. Start at pump three instead. The tank never goes negative on the way around, and it is exactly empty when the truck gets back. So the answer is pump three.
Example 2
gas = [2,3,4]cost = [3,4,3]return = -1All the pumps together give less fuel than the whole circuit needs. No starting pump can make it around, so you return minus one.
Constraints
1 <= gas.length = cost.length <= 10^5.0 <= gas[i], cost[i] <= 10^9.
More Apple interview questions
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge Two Strings by Maximum Boundary OverlapOA · Seen Sep 2026
- Collect Letters Along a Unique Grid PathOA · Seen Aug 2025
- Maximum Weight in Two BagsOA · Seen Aug 2025
- Ignore SectionsOA · Seen Mar 2024
- House Robber IIOA · Seen Nov 2021
- Clone an Undirected Graph StateOA · Seen Mar 2021
- Longest Increasing Subsequence LengthOA · Seen Feb 2021
- Maximum Later DifferenceOA · Seen Feb 2021
- Topological OrderingPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Earn the Most 🐝Capital One · OACapital One interview questions
- Minimum Cost to Merge Values into OnePayPal · OAPayPal interview questions
- Minimum Operations to Sort with Rotations Then SwapsBank of New York Mellon · OA
- Minimum Cost of Left and Right PropagationAmazon · OA
- Minimum Rounds to Complete All TasksInfosys · OAInfosys interview questions
- Reschedule Meetings for Maximum Free TimeFivetran · OAFivetran interview questions
- Maximum Easy Tasks After RearrangingIBM · OAIBM interview questions
- Minimum Cost K-Capable ModelsMicrosoft · OAMicrosoft interview questions
- Maximum ScoreNVIDIA · OANVIDIA interview questions
- Maximum Distinct Values After Unit AdjustmentsBirla Pivot · OA