Gas Station
Problem Statement
There are n gas stations on a circular road. Station i gives gas[i] litres of fuel. Driving from station i to the next station takes cost[i] litres. Your tank has no size limit, and you start with an empty tank at one of the stations.
Return the index of a station where you can start and drive once all the way around the circle, going the same direction at every step. If no start works, return -1. The input is set up so that at most one answer exists.
Two arrays gas and cost of the same length n.
The index of the starting station, or -1 if no start works.
Start at station 3 with 4 litres. Each leg uses its cost and the next station refills the tank. You reach station 3 again with exactly 0 litres left, so the trip works.
The total fuel is 9, but the total cost is 10. No start can cover the whole circle.
- • 1 ≤ n ≤ 10^5
- • `gas` and `cost` both have length `n`.
- • 0 ≤ gas[i], cost[i] ≤ 10^4
- • The input is set up so that the answer is unique, if there is one.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Try each station as the start and simulate the whole loop
Track the total and a running tank; when the tank drops below 0, the next station becomes the start
For each start s, drive around the circle, filling up at each station and then paying the cost to reach the next one. If the tank ever goes below 0, this start fails. If you finish the loop with the tank at 0 or more, return s. If no start passes, return -1.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Greedy translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.