AlgoTales · Roadmap

Frog jump

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Frog jump finds the cheapest way along a row of stones when from each stone you can hop 1 or 2 places and every landing has a cost. The cost to reach a stone is the cheaper of the two ways to arrive. It is the simplest model of finding the cheapest route through a chain of steps.

Practical use cases

  • Web app: Cheapest bus or train hop route. A travel app shows fares between consecutive stops, and you can skip a stop by taking a longer ticket. For each stop it keeps the cheapest total cost to get there, choosing the better of the previous stop or the one before. The traveller sees the cheapest plan to the last stop immediately. When a fare changes, the app reruns the pass and updates the cheapest plan instantly, instead of someone rechecking every possible combination of tickets.
  • Web app: Fitness app hiking plan. A hiking app rates each waypoint by effort, and the walker can skip one waypoint at a time. The app calculates the least total effort route to the summit with one pass over the list. Walkers can also see the effort total for the plan and compare it with the alternative of taking every waypoint, which makes the suggestion easy to trust.
  • System: Platform-game bots and robot walkers. A bot in a platform game decides which platforms to land on to lose the least health. Robot walkers choose footholds in the same way. Each of these remembers the cheapest cost for the stones behind it, so the decision at every new stone is a quick comparison rather than a fresh search of the whole path.

The story: The Frog in the Monsoon Pond

After the first monsoon rain, the pond behind Mira's school filled up and a line of stones stuck out of the water, each at a different height. A tiny green frog sat on the first stone and wanted to reach the last, where the dragonflies were.

The frog could jump to the very next stone or skip one. A jump cost energy equal to how different the heights were: a jump between equal-height stones was free, a jump from a low stone to a tall one was tiring. "Which stones should the frog use to waste the least energy?" asked Mrs. Sharma, drawing the pond on the blackboard.

Kabir tried to list all frog paths and got dizzy. Mira, once again, asked only about the last jump. "To reach stone 5, the frog came from stone 4 or from stone 3. Add the energy used to reach that stone to the cost of the last jump. Pick the cheaper." The same sentence works for every stone.

The only things a jump cost depends on are the two stones involved, so each box in the table needs just two earlier boxes. This is the classic Frog Jump problem: one-dimensional DP where the "price" of a move comes from the data, not from the position.

How to spot this problem, and where you need it

You are moving along a line of steps where each step has a cost and you may skip over some, and you need the least total cost to the end.

Signs you need it

  • The problem has a list of costs or heights, and allowed jumps of 1 or 2 (or a small number k) positions.
  • Always taking the cheapest next step does not give the cheapest total, because skipping can be better.
  • The question asks for the "minimum total cost" or "minimum energy" to reach the last item.

Where to use it in a project

  • Planning cheapest itineraries along an ordered list of stops.
  • Optimising effort, cost or time along a sequence of stages in a workflow.

The solution

Say the cost to reach the first stone is 0. For each later stone, work out the cost to arrive from one stone back and from two stones back, adding the jump cost each time. Store the smaller of the two as the cost for this stone. Continue to the last stone, where the stored value is the cheapest total. Only the last two values are needed to continue.

Payoff: Before: trying every possible hop pattern, about a million for 30 stones. After: a single pass of 30 steps.

Explain it like I am 8

A frog crosses stepping stones. For each stone, it asks: "Which of the two stones behind me is the cheapest place to jump from?" It remembers how tired it already was at each stone, so it never has to retry old routes.

How it works, step by step

  1. State: dp[i] = the least energy needed to reach stone i.
  2. Base case: dp[0] = 0, because the frog starts there.
  3. Transition: dp[i] = min(dp[i-1] + |h[i]-h[i-1]|, dp[i-2] + |h[i]-h[i-2]|). (|x| just means "ignore the minus sign".)
  4. Guard stone 1: it has no stone two back, so it only uses the first option.
  5. The answer is the last box. Only the last two boxes are ever read, so two variables also work.

The code in four languages

PHP

<?php
// Frog Jump: least total energy to reach the last stone.
// A jump of 1 or 2 stones costs the height difference between the stones.
function frogEnergy(array $h): int {
    $n = count($h);
    $dp = array_fill(0, $n, 0);                  // dp[0] = 0: the frog starts there
    for ($i = 1; $i < $n; $i++) {
        $oneJump = $dp[$i - 1] + abs($h[$i] - $h[$i - 1]);
        $twoJump = PHP_INT_MAX;                  // stone 1 has no "two back" option
        if ($i >= 2) $twoJump = $dp[$i - 2] + abs($h[$i] - $h[$i - 2]);
        $dp[$i] = min($oneJump, $twoJump);
    }
    return $dp[$n - 1];
}

echo frogEnergy([30, 10, 60, 10, 60, 50]), "\n";   // 40
echo frogEnergy([10, 20, 30, 10]), "\n";            // 20

JavaScript

// Frog Jump: least total energy to reach the last stone.
// A jump of 1 or 2 stones costs the height difference between the stones.
function frogEnergy(h) {
  const n = h.length;
  const dp = new Array(n).fill(0);               // dp[0] = 0: the frog starts there
  for (let i = 1; i < n; i++) {
    const oneJump = dp[i - 1] + Math.abs(h[i] - h[i - 1]);
    let twoJump = Infinity;                      // stone 1 has no "two back" option
    if (i >= 2) twoJump = dp[i - 2] + Math.abs(h[i] - h[i - 2]);
    dp[i] = Math.min(oneJump, twoJump);
  }
  return dp[n - 1];
}

console.log(frogEnergy([30, 10, 60, 10, 60, 50]));   // 40
console.log(frogEnergy([10, 20, 30, 10]));            // 20

Java

public class Main {
    // Frog Jump: least total energy to reach the last stone.
    // A jump of 1 or 2 stones costs the height difference between the stones.
    static int frogEnergy(int[] h) {
        int n = h.length;
        int[] dp = new int[n];                       // dp[0] = 0: the frog starts there
        for (int i = 1; i < n; i++) {
            int oneJump = dp[i - 1] + Math.abs(h[i] - h[i - 1]);
            int twoJump = Integer.MAX_VALUE;         // stone 1 has no "two back" option
            if (i >= 2) twoJump = dp[i - 2] + Math.abs(h[i] - h[i - 2]);
            dp[i] = Math.min(oneJump, twoJump);
        }
        return dp[n - 1];
    }

    public static void main(String[] args) {
        System.out.println(frogEnergy(new int[]{30, 10, 60, 10, 60, 50}));   // 40
        System.out.println(frogEnergy(new int[]{10, 20, 30, 10}));           // 20
    }
}

Go

package main

import (
	"fmt"
	"math"
)

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

// Frog Jump: least total energy to reach the last stone.
// A jump of 1 or 2 stones costs the height difference between the stones.
func frogEnergy(h []int) int {
	n := len(h)
	dp := make([]int, n) // dp[0] = 0: the frog starts there
	for i := 1; i < n; i++ {
		oneJump := dp[i-1] + abs(h[i]-h[i-1])
		twoJump := math.MaxInt // stone 1 has no "two back" option
		if i >= 2 {
			twoJump = dp[i-2] + abs(h[i]-h[i-2])
		}
		dp[i] = min(oneJump, twoJump)
	}
	return dp[n-1]
}

func main() {
	fmt.Println(frogEnergy([]int{30, 10, 60, 10, 60, 50})) // 40
	fmt.Println(frogEnergy([]int{10, 20, 30, 10}))         // 20
}

Time: O(n) · Extra space: O(n). One cheap calculation per stone. Keeping only the last two boxes brings space down to O(1).

Watch out for

  • Reading dp[i-2] for stone 1, which reaches outside the table. Guard it.
  • Forgetting the absolute value, so a downhill jump looks like it gives you energy back.
  • Comparing only the previous stone (greedy). A two-stone jump over a tall stone can be much cheaper.

Quick check

  1. From which stones can the frog reach stone 5?
    • Any earlier stone
    • Only stone 4
    • Stone 4 or stone 3
  2. What is dp[0] in frog jump?
    • 0, because it starts there
    • The height of stone 0
    • Infinity
  3. Heights [10, 20, 30, 10]. Which route is cheapest?
    • 0 to 1 to 2 to 3, costing 40
    • 0 to 2 to 3, costing 40
    • 0 to 1 to 3, costing 20