ExamAdda Logo

Gas Station

Easy

There are n gas stations arranged in a circular route.

You are given two integer arrays gas and cost, where:

• gas[i] is the amount of gas available at the ith station.
• cost[i] is the amount of gas required to travel from station i to station (i + 1).

You have an unlimited gas tank and start with an empty tank.

Return the starting gas station's index if you can travel around the circuit exactly once in the clockwise direction.

If it is impossible to complete the circuit, return -1.

If a solution exists, it is guaranteed to be unique.

Example 1

Input

5
1 2 3 4 5
3 4 5 1 2

Output

3

Explanation

Starting from station 3:

Tank = 4 - 1 = 3

Tank = 3 + 5 - 2 = 6

Tank = 6 + 1 - 3 = 4

Tank = 4 + 2 - 4 = 2

Tank = 2 + 3 - 5 = 0

The entire circuit can be completed successfully.

Example 2

Input

3
2 3 4
3 4 3

Output

-1

Explanation

The total amount of gas is less than the total travel cost.

Therefore, completing the circuit is impossible.

Constraints

n == gas.length == cost.length
1 ≤ n ≤ 10⁵
0 ≤ gas[i]
cost[i] ≤ 10⁴

Hints:

Hint 1

If the total amount of gas is less than the total cost, completing the circuit is impossible.

Hint 2

Traverse the stations while maintaining the current fuel balance. If the balance becomes negative, none of the previous stations can be the answer. Reset the starting station to the next index.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 4, 2026

Last updated

Aug 4, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output