Python 3D Academyবাংলা

Jump game and gas station

🌍 In real life. Children cross a shallow stream on a line of stepping stones. Each stone is painted with a number: from it, you can jump up to that many stones ahead. Can you get from the first stone to the last? You don't need to plan every jump. Walk along and remember one thing: the farthest stone any jump so far could reach.

The idea in one sentence: the stones you can reach always form one unbroken stretch from the start, so keeping just the farthest reach tells you everything; if you ever stand past it, you are stuck.

Its words:

  • reach: the farthest index some sequence of jumps can land on
  • jump length: nums[i], the most stones you may jump from stone i (any shorter jump is allowed too)
  • stuck: a stone beyond the reach; no jump can land there, nor anywhere after

Step by step:

  1. start with reach 0
  2. go through the stones in order; if a stone's index is more than the reach, answer False
  3. otherwise update reach to the larger of reach and i + nums[i]
  4. if you get through every stone, answer True

On the stones [2, 3, 1, 1, 4], stone 1 already reaches the end:

On [3, 2, 1, 0, 4] every path leads to stone 3, which has a 0 on it. The reach stays 3, and stone 4 is past it:

Why the farthest reach is enough. If you can reach stone r, you can reach every stone before it: the jump that passes over them could have been shorter. So the reachable stones are exactly 0 up to the reach, and greedy never has to remember which jump got there.

The same trick on a ring of fuel stations. A delivery van drives round a ring road with fuel stations. At station i it gets gas[i] litres, and driving to the next station uses cost[i]. From which station can it start with an empty tank and get all the way round? If the whole loop has less fuel than it uses, no start works. Otherwise drive from station 0 keeping the tank; whenever the tank goes below zero at station i, no station up to i can be the start (each of them would arrive at i with no more fuel), so try i + 1 with an empty tank.

What it costs, by counting. Both look at each stone or station once: O(n) time and O(1) memory. For 100,000 stations, 100,000 steps. Trying each start and driving the loop would be O(n²), 10,000,000,000 steps.

def can_jump(nums):
    reach = 0                                  # the farthest stone we know we can get to
    for i, step in enumerate(nums):
        if i > reach:                          # this stone is past every jump: stuck
            return False
        reach = max(reach, i + step)           # from here we can get to i + step
    return True

def gas_station(gas, cost):
    if sum(gas) < sum(cost):                   # not enough fuel in the whole loop
        return -1
    start, tank = 0, 0
    for i in range(len(gas)):
        tank += gas[i] - cost[i]
        if tank < 0:                           # can't reach i + 1 from start:
            start, tank = i + 1, 0             # no stop up to i can be the start
    return start

print(can_jump([2, 3, 1, 1, 4]), can_jump([3, 2, 1, 0, 4]))
print(gas_station([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]))

Mistakes and edge cases.

  • a single stone: you are already on the last stone, so the answer is True
  • checking only for zeros: a 0 is a problem only if nothing jumps over it; [2, 0, 0] can reach the end
  • the reach going down: always take max; a short jump later must not shrink what an earlier stone reached
  • forgetting the total check: in the fuel ring, the running tank alone can return a start even when the loop has too little fuel overall

Quiz

  1. What does this print?

    def can_jump(nums):
        reach = 0                                  # the farthest stone we know we can get to
        for i, step in enumerate(nums):
            if i > reach:                          # this stone is past every jump: stuck
                return False
            reach = max(reach, i + step)           # from here we can get to i + step
        return True
    
    print(can_jump([1, 0, 1]))
  2. Why is the farthest reach all greedy needs to remember?

    • Every stone before a reachable stone is reachable too
    • The biggest number on a stone decides the answer
    • Jumps are always the full length
  3. What does this print?

    def gas_station(gas, cost):
        if sum(gas) < sum(cost):                   # not enough fuel in the whole loop
            return -1
        start, tank = 0, 0
        for i in range(len(gas)):
            tank += gas[i] - cost[i]
            if tank < 0:                           # can't reach i + 1 from start:
                start, tank = i + 1, 0             # no stop up to i can be the start
        return start
    
    print(gas_station([2, 3, 4], [3, 4, 3]))
  4. Starting at station 0, the tank first goes below zero after station 2. What next?

    • Try station 3 with an empty tank: stations 0, 1 and 2 can't be the start
    • Try station 1
    • Answer −1
  5. can_jump([3, 0, 0, 0]) answers False. Which line is wrong?

    def can_jump(nums):
        reach = 0
        for i, step in enumerate(nums):
            if i > reach:
                return False
            reach = i + step
        return True

Coding tasks

  1. Write can_jump(nums): you start on stone 0, and from stone i you may jump forward up to nums[i] stones. Return True if you can reach the last stone, else False.

  2. Write gas_station(gas, cost): stations stand in a ring. At station i you get gas[i] litres, and driving on to station i + 1 (or back to 0 from the last) uses cost[i]. Return the index of the station to start from with an empty tank to drive all the way round, or -1 if none works. When an answer exists, it is the only one.