Python coding

Where to start a full lap

Charging stations sit around a circular track, numbered in driving order. At station i you pick up charge[i] units of energy, and the drive from station i to the next one (after the last comes station 0) uses drain[i] units. You begin at a station of your choice with an empty battery of unlimited capacity. Return the smallest station index from which you can drive one full lap without the battery ever going below zero, or -1 if no station works.

Both lists have the same length (at least 1) and non-negative values. Aim for one pass.

Besides the tests, one large input (4,000 stations) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • lap_start([4,1,6,2], [5,3,2,3]) → 2
  • lap_start([3,1,1], [2,2,2]) → -1
  • lap_start([4,1,1,2], [2,2,2,2]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Look at the net gain per station, charge[i] - drain[i]. If the nets of the whole lap sum to less than zero, no start can work.

Hint 2

Drive from a candidate start with a running battery. If it drops below zero after station i, every station from the candidate to i also fails: move the candidate to i + 1.

Hint 3

The trap is trusting a local pick, like the first station with a positive net or the one with the largest. Only the reset rule, together with the total check, is safe.

Solution and why it works
pythonO(n) · O(1)
def lap_start(charge: list[int], drain: list[int]) -> int:
    total = battery = start = 0
    for i in range(len(charge)):
        net = charge[i] - drain[i]
        total += net
        battery += net
        if battery < 0:                  # no station in start..i can be the answer
            start, battery = i + 1, 0
    return start if total >= 0 else -1

If a drive from start first dips below zero after station i, no station in start..i can be the answer: you reached each of them with a battery of zero or more, so leaving from one with an empty battery can only do worse. That lets the candidate jump to i + 1 and makes one pass enough. If the total net is non-negative, the last candidate completes the lap, and it is the smallest valid index. The trap is skipping the total check, or picking the largest net.