BackhardGreedyAppleMorgan Stanley

Subtree Height Evaluator Resolver 5 Solution

Problem Statement

You are given two integer arrays gas[0…N‑1] and cost[0…N‑1] that describe N stations placed on a circular route. At station i you can collect exactly gas[i] units of fuel, and traveling from station i to the next station (i+1 mod N) consumes cost[i] units of fuel. Starting with an empty tank at any station, you may move clockwise and must complete a full loop without the fuel level ever dropping below zero. Return the smallest index of a station from which such a tour is possible. If no starting station allows a complete circuit, return -1.

Your algorithm must run in O(N) time and O(1) extra space, i.e., a single pass greedy solution that tracks the cumulative surplus and resets when the current segment becomes infeasible.

Example 1
Input
5 1 2 3 4 5 3 4 5 1 2
Output
3

Explanation: Total gas = 15, total cost = 15, so a solution exists. Starting at index 0 fails after station 2 (fuel becomes -1). Resetting the start to index 3, the cumulative surplus never becomes negative: after station 3 fuel = 4‑1=3, after station 4 fuel = 3+5‑2=6, after station 0 fuel = 6+1‑3=4, after station 1 fuel = 4+2‑4=2, after station 2 fuel = 2+3‑5=0. The circuit completes, thus the answer is 3.

Example 2
Input
3 2 3 4 3 4 3
Output
-1

Explanation: Total gas = 9, total cost = 10, which is insufficient to cover the whole route. No starting point can succeed, so the correct output is -1.

Example 3
Input
4 5 1 2 3 4 4 1 5
Output
0

Explanation: Total gas = 11, total cost = 14, but the greedy scan shows a feasible start at index 0: after station 0 fuel = 5‑4=1, after station 1 fuel = 1+1‑4=-2 (negative). Because the deficit occurs, we shift the start to index 2 and reset surplus to 0. Continuing from index 2: fuel = 2‑1=1, after station 3 fuel = 1+3‑5=-1 (negative) → shift start to index 0 again, but now the cumulative surplus from index 0 to the end of the array is non‑negative (5‑4 + 1‑4 + 2‑1 + 3‑5 = 0). Since the total surplus is zero, the earliest feasible start is index 0.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= gas[i] <= 10^9
  • -10^9 <= cost[i] <= 10^9
  • All calculations fit into 64‑bit signed integers
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Subtree Height Evaluator Resolver 5 — Problem Statement & Solution Guide

GreedyHardGas Station Circuit
TimeO(N)
|
SpaceO(1)

Problem Description

You are given two integer arrays gas[0…N‑1] and cost[0…N‑1] that describe N stations placed on a circular route. At station i you can collect exactly gas[i] units of fuel, and traveling from station i to the next station (i+1 mod N) consumes cost[i] units of fuel. Starting with an empty tank at any station, you may move clockwise and must complete a full loop without the fuel level ever dropping below zero. Return the smallest index of a station from which such a tour is possible. If no starting station allows a complete circuit, return -1.

Your algorithm must run in O(N) time and O(1) extra space, i.e., a single pass greedy solution that tracks the cumulative surplus and resets when the current segment becomes infeasible.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Subtree Height Evaluator Resolver 5"

hard

WHY DOES IT MATTER?

The pattern exemplifies greedy elimination on circular sequences, a technique that appears in load‑balancing, circular buffer management, and network token‑ring protocols where a single pass must decide feasibility.

OPTIMIZATION CHALLENGE

The breakthrough is recognizing that a negative cumulative balance invalidates all stations within that segment, allowing us to skip them entirely instead of re‑checking each one, collapsing O(N^2) work into O(N).

REAL-WORLD CONNECTION

Imagine a delivery truck that must pick up parcels (gas) and deliver them to the next depot (cost). The algorithm tells you the depot where the driver should begin so that the truck never runs out of fuel, mirroring route‑planning in logistics and distributed token‑passing systems.

During an interview, compute total surplus first; if it's negative, you can immediately answer "no solution" and save time. Then use a single loop with two variables (tank and start) – no extra arrays needed.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(1)

Core Theory — Why This Approach?

The gas‑station problem is a classic example of a circular array feasibility check that can be solved in linear time using a greedy sweep. The naive view is to try every station as a starting point and simulate the trip, which leads to O(N^2) time and quickly becomes infeasible for N up to 10^5 or more. The key observation is that if the total amount of gas across all stations is less than the total travel cost, no starting point can succeed, because the deficit cannot be compensated regardless of the order of visits. When the total surplus is non‑negative, a single pass can identify a viable start: while traversing the stations, maintain a running tank balance; if it ever drops below zero, any station between the current start and the failure point cannot be a valid start, so we shift the start to the next index and reset the balance. This greedy elimination works because the deficit encountered proves that every station in the failed segment would also encounter a deficit earlier, making them impossible candidates. The algorithm thus reduces the problem to a single O(N) scan with O(1) extra memory.

Interview Questions on This Problem

Q1How would you determine if a circular gas station route has any feasible starting point in O(N) time?

First compute the total gas minus total cost; if negative, return -1. Then iterate once, keeping a running tank balance. When the balance becomes negative, move the start index to the next station and reset the balance to zero. After the loop, the start index is the answer.

Q2Why does resetting the start index after a deficit guarantee that earlier stations cannot be valid starts?

Because the deficit means the cumulative sum from the current start to the failure point is negative. Any station inside that segment would inherit the same negative prefix before reaching the failure point, so none can succeed; only stations after the failure point remain possible.

Q3Can there be multiple valid starting stations? How would you modify the algorithm to list all of them?

Yes, when the total surplus is zero, any station that never causes the running balance to dip below zero in a second pass (starting from the found start) is also valid. After finding one feasible start, perform another linear scan recording indices where the cumulative balance never goes negative relative to that start.

Examples

Example 1

Input

5
1 2 3 4 5
3 4 5 1 2

Output

3

Explanation: Total gas = 15, total cost = 15, so a solution exists. Starting at index 0 fails after station 2 (fuel becomes -1). Resetting the start to index 3, the cumulative surplus never becomes negative: after station 3 fuel = 4‑1=3, after station 4 fuel = 3+5‑2=6, after station 0 fuel = 6+1‑3=4, after station 1 fuel = 4+2‑4=2, after station 2 fuel = 2+3‑5=0. The circuit completes, thus the answer is 3.

Example 2

Input

3
2 3 4
3 4 3

Output

-1

Explanation: Total gas = 9, total cost = 10, which is insufficient to cover the whole route. No starting point can succeed, so the correct output is -1.

Example 3

Input

4
5 1 2 3
4 4 1 5

Output

0

Explanation: Total gas = 11, total cost = 14, but the greedy scan shows a feasible start at index 0: after station 0 fuel = 5‑4=1, after station 1 fuel = 1+1‑4=-2 (negative). Because the deficit occurs, we shift the start to index 2 and reset surplus to 0. Continuing from index 2: fuel = 2‑1=1, after station 3 fuel = 1+3‑5=-1 (negative) → shift start to index 0 again, but now the cumulative surplus from index 0 to the end of the array is non‑negative (5‑4 + 1‑4 + 2‑1 + 3‑5 = 0). Since the total surplus is zero, the earliest feasible start is index 0.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= gas[i] <= 10^9
  • -10^9 <= cost[i] <= 10^9
  • All calculations fit into 64‑bit signed integers

Optimal Approach & Strategy

Perform a single pass, tracking cumulative surplus; when it becomes negative, move the start to the next index and reset the surplus, yielding O(N) time and O(1) space.

Brute Force Approach

Try each station as a start, simulate the full circle, and check if the tank ever goes negative; this requires O(N^2) time.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   let sum = 0;
   for (let num of nums) {
       sum += num;
   }
   let height = 0;
   for (let i = 0; i < nums.length; i++) {
       height += nums[i];
   }
   return height;
}

Asked in Top Tech Interviews

AppleMorgan Stanley

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.