Transition
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The transition is the rule that builds the answer for one state out of answers to smaller states, like "best here equals the better of two earlier choices plus this cost". It is a single recipe reused for every cell. Once you have it, the code is short.
Practical use cases
- Web app: Cheapest fare across connecting trains. A booking site shows the cheapest way to reach a city through connecting trains. For each station the rule is: cheapest cost here equals the smallest of (cheapest cost to each previous station plus the fare from there). Applying that one rule at every station yields the best total.
- Web app: Shipping cost calculator. A courier website prices parcels with a base fee plus a charge per band of weight. The cost for a 10 kg parcel is the cheaper of "cost for 8 kg plus the 2 kg band" or "cost for 5 kg plus the 5 kg band". One transition line replaces a page of if-else rules. When the courier changes its price bands, only that one line changes and every weight from 1 to 50 kg is priced correctly again, with no hunting through old rules.
- System: Project scheduling. Project planning tools work out the earliest finish of each task as the latest finish among its prerequisites plus its own duration. That is a transition applied task by task. Each of these systems writes one rule describing how a bigger answer is made from smaller ones and then applies it again and again until the whole answer appears.
The story: Stepping Stones at the Mela
At the village mela, Kabir found a pond with a line of stepping stones. A signboard said: "Each stone charges a small fee when you stand on it. You may hop to the next stone or skip one. Cross as cheaply as you can!" The fees were 10, 15, 20, 5, 10 and 25 paise.
Kabir tried every path with a pencil and got a mess. Mira stopped him: "Forget the whole pond. Stand on stone number 4 and ask only: how did I get here? From stone 3, or from stone 2. Nothing else is possible." So the cheapest way to stand on stone 4 is its own fee plus the cheaper of the two ways to arrive.
That one sentence worked for every stone. Stone 2 looks at stones 1 and 0, stone 3 looks at stones 2 and 1, and so on. Mira had found the rule that builds a bigger answer from smaller ones.
That rule is the transition (many books call it the recurrence). Once you have the state ("cheapest total standing on stone i") and the transition ("own fee + the cheaper of the last two"), the rest is just filling the table.
How to spot this problem, and where you need it
You know what each stored answer means but not how to compute one from the others, and you end up with piles of special-case code.
Signs you need it
- At each step you have a small number of choices, like take or skip, come from the left or from above, jump 1 or 2.
- You can describe the answer for step i in words using the answers for steps just before it.
- Your code has many if-else branches that all look like variations of one idea.
Where to use it in a project
- Pricing engines where the price for a size is built from the price of smaller sizes.
- Planning features such as cheapest route, minimum time or best score, where each step picks the better of a few options.
The solution
Look at the very last decision that leads to the current state. List every possible last move. For each move, find the smaller state it came from and the cost of the move. Combine them, usually by taking the minimum, maximum or sum, and that is your transition. Write it once as a single formula inside the loop, and the same line then works for every state.
Payoff: Before: dozens of if-else rules for each case. After: a one-line rule applied in a loop, and a fix in one place fixes everything.
Explain it like I am 8
The transition is a recipe card: "To make a big cake box, take the last two boxes, pick the better one, and add this box's price." The same card works for every box, so you only need to write it once.
How it works, step by step
- Stand on the box you want to fill and ask: "what was the very last move that brought me here?"
- List every possible last move. Here: a 1-stone hop or a 2-stone hop.
- Turn each move into the earlier box it came from, and the extra cost of making that move.
- Combine them with the question's goal: take the minimum for cheapest, the maximum for best, or the sum for counting ways.
- Write it as one line of code. Here:
dp[i] = cost[i] + min(dp[i-1], dp[i-2]).
The code in four languages
PHP
<?php
// Transition: dp[i] = cost[i] + min(dp[i-1], dp[i-2])
// dp[i] = cheapest total to be standing on stone i.
function cheapestCrossing(array $cost): int {
$n = count($cost);
$dp = [];
$dp[0] = $cost[0]; // start on stone 0
$dp[1] = $cost[1]; // or start on stone 1
for ($i = 2; $i < $n; $i++) {
$dp[$i] = $cost[$i] + min($dp[$i - 1], $dp[$i - 2]); // the transition
}
return min($dp[$n - 1], $dp[$n - 2]); // far bank: from last or second-last stone
}
echo cheapestCrossing([10, 15, 20, 5, 10, 25]), "\n"; // 30 (stones 1, 3, 4)JavaScript
// Transition: dp[i] = cost[i] + min(dp[i-1], dp[i-2])
// dp[i] = cheapest total to be standing on stone i.
function cheapestCrossing(cost) {
const n = cost.length;
const dp = [];
dp[0] = cost[0]; // start on stone 0
dp[1] = cost[1]; // or start on stone 1
for (let i = 2; i < n; i++) {
dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]); // the transition
}
return Math.min(dp[n - 1], dp[n - 2]); // far bank: from last or second-last stone
}
console.log(cheapestCrossing([10, 15, 20, 5, 10, 25])); // 30 (stones 1, 3, 4)Java
public class Main {
// Transition: dp[i] = cost[i] + min(dp[i-1], dp[i-2])
// dp[i] = cheapest total to be standing on stone i.
static int cheapestCrossing(int[] cost) {
int n = cost.length;
int[] dp = new int[n];
dp[0] = cost[0]; // start on stone 0
dp[1] = cost[1]; // or start on stone 1
for (int i = 2; i < n; i++) {
dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]); // the transition
}
return Math.min(dp[n - 1], dp[n - 2]); // far bank: from last or second-last stone
}
public static void main(String[] args) {
System.out.println(cheapestCrossing(new int[]{10, 15, 20, 5, 10, 25})); // 30 (stones 1, 3, 4)
}
}Go
package main
import "fmt"
// Transition: dp[i] = cost[i] + min(dp[i-1], dp[i-2])
// dp[i] = cheapest total to be standing on stone i.
func cheapestCrossing(cost []int) int {
n := len(cost)
dp := make([]int, n)
dp[0] = cost[0] // start on stone 0
dp[1] = cost[1] // or start on stone 1
for i := 2; i < n; i++ {
dp[i] = cost[i] + min(dp[i-1], dp[i-2]) // the transition
}
return min(dp[n-1], dp[n-2]) // far bank: from last or second-last stone
}
func main() {
fmt.Println(cheapestCrossing([]int{10, 15, 20, 5, 10, 25})) // 30 (stones 1, 3, 4)
}Time: O(n) · Extra space: O(n). One cheap comparison per stone. The transition looks at a fixed number of earlier boxes, so time stays linear.
Watch out for
- Missing a possible last move (for example forgetting the 2-step hop), which gives an answer that is too big or too small.
- Using the wrong combiner. Cheapest wants
min, best wantsmax, number of ways wants+. - Forgetting to add the cost of the move itself (here, the fee of the stone you land on).
Quick check
- What does the transition describe?
- The first box of the table
- How a bigger answer is built from smaller ones
- How to print the table
- To count the number of ways, the transition usually combines options with…
- max
- min
- plus (add them up)
- Fees 10 and 15 at the start, then 20. dp for stone 2 is?
- 30
- 45
- 20