BackhardGreedyGoogleMicrosoft

Subtree Height Evaluator Resolver 3 Solution

Problem Statement

You are provided with a circular array of integers gas of length N, where gas[i] represents the net fuel change (gain or loss) at station i. A vehicle starts with an empty tank and must complete a full circuit of the array. The vehicle can only proceed from station i to i+1 if its current fuel level is non-negative. Your task is to determine the unique starting index from which the vehicle can complete the entire circuit without running out of fuel. If no such starting index exists, return -1. The solution must leverage the properties of cumulative sums to identify the valid starting point in linear time.

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

Explanation: Calculate net fuel at each station: [1-2, -2-3, 3-4, 4-5, -5-6] = [-1, -5, -1, -1, -11]. The total sum is -19, which is negative. Since the total fuel is insufficient to cover the total cost, it is impossible to complete the circuit from any starting point. Return -1.

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

Explanation: Net fuel array: [1, -3, 1, -2, 3]. Total sum is 0. Start at index 0: fuel=1, next fuel=1-3=-2 (fail). Start at index 1: fuel=-3 (fail immediately). Start at index 2: fuel=1, next fuel=1-2=-1 (fail). Start at index 3: fuel=-2 (fail immediately). Start at index 4: fuel=3, next fuel=3+1=4, next fuel=4-3=1, next fuel=1+1=2, next fuel=2-2=0. All fuel levels are non-negative. Return 4.

Example 3
Input
gas = [2, 3, 4], cost = [3, 4, 3]
Output
2

Explanation: Net fuel array: [-1, -1, 1]. Total sum is -1. Wait, sum is -1-1+1 = -1. This is negative. Let's adjust example to be valid. Revised Input: gas = [2, 3, 4], cost = [2, 3, 3]. Net: [0, 0, 1]. Total sum 1. Start 0: fuel 0, next 0, next 1. Valid. Return 0. Let's use a different valid one. Input: gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]. Net: [-2, -2, -2, 3, 3]. Total 0. Start 0: fail. Start 1: fail. Start 2: fail. Start 3: fuel 3, next 3+3=6, next 6-2=4, next 4-2=2, next 2-2=0. Valid. Return 3.

Constraints

  • 1 <= gas.length <= 10^5
  • 0 <= gas[i] <= 10^4
  • 0 <= cost[i] <= 10^4
  • gas.length == cost.length
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 3 — Problem Statement & Solution Guide

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

Problem Description

You are provided with a circular array of integers gas of length N, where gas[i] represents the net fuel change (gain or loss) at station i. A vehicle starts with an empty tank and must complete a full circuit of the array. The vehicle can only proceed from station i to i+1 if its current fuel level is non-negative. Your task is to determine the unique starting index from which the vehicle can complete the entire circuit without running out of fuel. If no such starting index exists, return -1. The solution must leverage the properties of cumulative sums to identify the valid starting point in linear time.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Subtree Height Evaluator Resolver 3"

hard

WHY DOES IT MATTER?

The greedy pattern here transforms a seemingly combinatorial search into a deterministic linear scan, teaching candidates how to eliminate impossible candidates early and avoid exhaustive enumeration—a skill crucial for performance‑critical code.

OPTIMIZATION CHALLENGE

The key insight is that a negative tank balance invalidates all stations within the current trial segment, allowing us to jump the start pointer forward in O(1) time instead of rechecking each station, collapsing O(N^2) work into a single O(N) pass.

REAL-WORLD CONNECTION

Think of a delivery truck refueling at stations around a city loop; the algorithm determines the optimal depot to start from so the truck never runs out, analogous to load balancing in circular buffers or token‑ring networks where resources must circulate without starvation.

During an interview, compute the total net fuel first; if it's negative, return -1 immediately. Otherwise, maintain a running tank and a candidate start index—reset both when the tank drops below zero. This two‑step check is both concise and bullet‑proof.

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 greedy feasibility check on a circular sequence. The naive intuition—trying every possible start and simulating the trip—fails because the time complexity explodes to O(N^2) for large N, making it impractical for constraints up to 10^5 or 10^6. The optimal greedy insight leverages the fact that if the total sum of gas[i] - cost[i] over the entire circuit is negative, no start can succeed, and if it is non‑negative, there exists exactly one feasible start. By scanning the array once while maintaining a running tank balance, we can discard any segment that leads to a negative balance because any start within that segment would also fail; the next viable candidate becomes the index immediately after the failure point. This single‑pass algorithm reduces the problem to O(N) time and O(1) extra space, embodying the greedy paradigm of making locally optimal decisions that guarantee a global solution.

The underlying theory rests on two invariants: (1) the cumulative deficit encountered up to a point determines that all indices before the current candidate are impossible starts, and (2) the overall feasibility is decided solely by the total net fuel. By resetting the tank to zero whenever it dips below zero and moving the start pointer forward, we ensure that the remaining unprocessed segment still holds the potential to satisfy the circuit, because any earlier deficit has already been accounted for in the total sum check. This elegant reduction from exponential to linear time is why the greedy approach is the de‑facto solution for this problem.

Interview Questions on This Problem

Q1How would you modify the algorithm if each station also had a maximum tank capacity constraint?

Track the current fuel level and cap it at the station's capacity after each refill; the greedy start‑selection logic remains unchanged because the feasibility still depends on total net fuel, but you must ensure the tank never exceeds the capacity during simulation, resetting the start when a capacity breach forces a negative effective balance.

Q2Can you prove that if the total net fuel is non‑negative, the start index found by the greedy scan is unique?

Assume two different starts both succeed; then the segment between them would have a net positive surplus, contradicting the greedy rule that any negative prefix forces the start to move past it. Hence only one index can satisfy the condition when the total sum is ≥ 0.

Q3Explain how you would adapt the solution for a distributed system where each node holds a segment of the circular array.

Each node computes its local sum and the minimum prefix sum of its segment; a coordinator aggregates these to compute the global total and identifies the first segment where the cumulative prefix becomes negative, then the start index is the first element after that segment. This mirrors the single‑pass greedy logic but distributed across nodes.

Examples

Example 1

Input

gas = [1, -2, 3, 4, -5], cost = [2, 3, 4, 5, 6]

Output

-1

Explanation: Calculate net fuel at each station: [1-2, -2-3, 3-4, 4-5, -5-6] = [-1, -5, -1, -1, -11]. The total sum is -19, which is negative. Since the total fuel is insufficient to cover the total cost, it is impossible to complete the circuit from any starting point. Return -1.

Example 2

Input

gas = [5, 1, 2, 3, 4], cost = [4, 4, 1, 5, 1]

Output

4

Explanation: Net fuel array: [1, -3, 1, -2, 3]. Total sum is 0. Start at index 0: fuel=1, next fuel=1-3=-2 (fail). Start at index 1: fuel=-3 (fail immediately). Start at index 2: fuel=1, next fuel=1-2=-1 (fail). Start at index 3: fuel=-2 (fail immediately). Start at index 4: fuel=3, next fuel=3+1=4, next fuel=4-3=1, next fuel=1+1=2, next fuel=2-2=0. All fuel levels are non-negative. Return 4.

Example 3

Input

gas = [2, 3, 4], cost = [3, 4, 3]

Output

2

Explanation: Net fuel array: [-1, -1, 1]. Total sum is -1. Wait, sum is -1-1+1 = -1. This is negative. Let's adjust example to be valid. Revised Input: gas = [2, 3, 4], cost = [2, 3, 3]. Net: [0, 0, 1]. Total sum 1. Start 0: fuel 0, next 0, next 1. Valid. Return 0. Let's use a different valid one. Input: gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]. Net: [-2, -2, -2, 3, 3]. Total 0. Start 0: fail. Start 1: fail. Start 2: fail. Start 3: fuel 3, next 3+3=6, next 6-2=4, next 4-2=2, next 2-2=0. Valid. Return 3.

Constraints

  • 1 <= gas.length <= 10^5
  • 0 <= gas[i] <= 10^4
  • 0 <= cost[i] <= 10^4
  • gas.length == cost.length

Optimal Approach & Strategy

Perform a single pass, maintaining a running fuel balance and a candidate start; reset both when the balance becomes negative, yielding O(N) time and O(1) extra space.

Brute Force Approach

Try every index as a starting point and simulate the whole circuit, resetting when fuel goes negative; this requires O(N^2) time in the worst case.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   let max = 0;
   function dfs(node, height) {
       if (node === null) {
           return height;
       }
       height++;
       max = Math.max(max, height);
       dfs(node.left, height);
       dfs(node.right, height);
       return max;
   }
   return dfs(nums[0], 0);
}

Asked in Top Tech Interviews

GoogleMicrosoft

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.