← JP Morgan Interview Insights
I knew this problem but still fumbled explaining my reasoning out loud.
Use a greedy approach: iterate through stations while tracking the current gas surplus and total surplus. If the current surplus drops below zero, reset the starting point to the next station and reset the current surplus. After one pass, if the total surplus is non-negative, return the last reset starting point; otherwise, return -1.
Pro tip: Mention that the problem is equivalent to finding the starting index in a circular array where the cumulative sum of (gas - cost) never drops below zero. Emphasize that the greedy choice is safe because if a valid tour exists, it must start after the last point where the cumulative sum was minimal.
Restate the problem: given arrays gas and cost, find the starting index for a circular tour with non-negative gas at all times. Clarify that if no solution exists, return -1.
Compute the total gas and total cost. If total gas < total cost, no solution exists; return -1 immediately.
Initialize start = 0, current_tank = 0, total_tank = 0. For each station i, update current_tank += gas[i] - cost[i] and total_tank += gas[i] - cost[i]. If current_tank < 0, set start = i + 1 and reset current_tank = 0.
After the loop, if total_tank >= 0, return start; otherwise, return -1. Explain why this works: the start is the first station after the last deficit.
State that the algorithm runs in O(n) time and O(1) space, which is optimal. Mention that a brute-force approach would be O(n^2).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.