{"id":"min-cost-climbing-stairs","title":"Min Cost Climbing Stairs","difficulty":"easy","patterns":["dp-1d"],"primaryConcept":"dp-1d-decision","concepts":["dp-1d-decision"],"problemForm":"core","companies":["Amazon","Google","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"cost","sizeMetric":"length","constraints":["non-negative"],"valueRange":{"min":0,"max":1000},"sizes":[8,16,32,64]},"description":"You are given an array `cost` where `cost[i]` is the price of stepping on stair `i`. After paying for a stair, you may climb either one or two stairs. You may start on stair `0` or stair `1`. Return the minimum cost needed to reach the top just beyond the last stair.","examples":[{"input":"cost = [10,15,20]","output":"15","explanation":"Start at stair 1, pay 15, then climb two steps to the top."},{"input":"cost = [1,100,1,1,1,100,1,1,100,1]","output":"6","explanation":"A low-cost route pays six total by stepping mostly on the stairs with cost 1."}],"constraints":[{"id":"2-len-cost-1000","text":"2 <= len(cost) <= 1000","check":{"kind":"sizeRange","target":"cost","measure":"arrayLength","min":2,"max":1000}},{"id":"0-cost-i-1000","text":"0 <= cost[i] <= 1000","check":{"kind":"valueRange","target":"cost","selector":"arrayItems","min":0,"max":1000}}],"starterCode":"class Solution:\n    def minCostClimbingStairs(self, cost: list[int]) -> int:\n        # Your code here\n        pass","functionName":"minCostClimbingStairs","testCases":[{"id":"1","input":{"cost":[10,15,20]},"expected":15,"description":"Start on stair 1 and jump directly to the top."},{"id":"2","input":{"cost":[1,100,1,1,1,100,1,1,100,1]},"expected":6,"description":"Choose the low-cost stairs while skipping expensive ones."},{"id":"3","input":{"cost":[1,2]},"expected":1,"description":"Two stairs: start on the cheaper stair that can reach the top."},{"id":"4","input":{"cost":[0,0,0,0]},"expected":0,"description":"Zero-cost stairs keep the answer at zero."},{"id":"5","input":{"cost":[5,10,5,10,5]},"expected":15,"description":"Alternating costs require comparing one-step and two-step arrivals."},{"id":"h1","input":{"cost":[1,1,1,1]},"expected":2,"description":"Uniform low costs."},{"id":"h2","input":{"cost":[1000,1,1000,1,1000,1]},"expected":3,"description":"Large alternating costs near the maximum value."},{"id":"h3","input":{"cost":[7,3,8,4,2,6]},"expected":9,"description":"Mixed values where the locally cheapest next stair is not always enough."},{"id":"h4","input":{"cost":[1,2,3,4,5,6]},"expected":9,"description":"A steadily increasing staircase still favors the cheaper prefix."},{"id":"h5","input":{"cost":[10,1,10,1,10,1]},"expected":3,"description":"Alternating spikes reward the cheapest alternating path."}],"hints":[{"level":1,"content":"Think of the top as a final position after the last index. To reach any position, you came from one or two positions behind it.","revealPattern":false},{"level":2,"content":"Let `dp[i]` be the cheapest cost to stand at position `i`. The cost to reach `i` compares paying for `i - 1` or paying for `i - 2`.","revealPattern":true},{"level":3,"content":"Seed `dp[0] = 0` and `dp[1] = 0`, then update `dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])`.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which shape should we build?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"recursive-bruteforce","name":"Recurse every climb","summary":"For each position ask the same min question recursively, with no memory between calls.","decisionReason":"The decomposition is right, but the call tree re-solves the same positions over and over, doubling per level to roughly O(2^n).","complexity":{"time":"O(2^n)","space":"O(n)"},"tradeoffs":["Runs in O(2^n) time and uses O(n) stack space."],"isOptimal":false},{"id":"dp-table","name":"Fill a cost table once","summary":"Compute the cheapest cost to stand at every position from the ground through the top, in order.","decisionReason":"Each position is solved once from its two predecessors, so the staircase fills in O(n) with the answers it reads always ready.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space for the table."],"isOptimal":true},{"id":"sort-costs","name":"Sort the stair costs","summary":"Reorder the stairs by price and step on the cheapest ones.","decisionReason":"Sorting discards position order, but a jump is only legal between adjacent positions, so the cheapest prices become unreachable.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Runs in O(n log n) time and destroys the position order the jumps depend on."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-dp","title":"Create the cost table","description":"Allocate a slot for every position from the ground through the top, and fill unsolved positions with a value larger than any real route.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_sentinel_indexed_state_store","scope":"init-dp","readMode":"dp-value-query-v1"}]},"commonMistakes":["Creating a table with only len(cost) slots","Starting every position at zero so the min comparisons never improve"],"hint":"The table needs one extra slot for the top, and unknown positions start at a sentinel cost.","semanticSpec":{"intent":"Initialize an indexed cost table for all stair positions including the top.","doneWhen":"The code creates a position-indexed table and gives unsolved positions a sentinel cost.","shouldFailWhen":"This step should fail if there is no indexed state store, or if every position starts as a solved zero.","roles":["cost table","top position","sentinel cost"],"mustProve":["An indexed state table is initialized.","Unsolved positions begin at a sentinel cost."],"mustNotAccept":["A single scalar with no indexed state.","A table that cannot represent an unknown minimum cost."]}},{"id":"set-base-case","title":"Seed the two starts","description":"Standing before stair 0 or before stair 1 costs nothing, so set both starting slots to zero.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_zero_index_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]},"commonMistakes":["Paying a price before the first move","Seeding only stair 0 and forgetting that starting on stair 1 is legal"],"hint":"Both legal starts arrive at zero cost before any stair is paid for.","semanticSpec":{"intent":"Seed the two zero-cost starting positions before the transitions begin.","doneWhen":"The indexed table holds a zero base case for the starts before the main loop.","shouldFailWhen":"This step should fail if no zero base case is written into the table.","roles":["base case","starting positions"],"mustProve":["The indexed state store receives a zero base case."],"mustNotAccept":["Leaving every table entry at the sentinel value."]}},{"id":"outer-loop","title":"Walk to each target position","description":"Move through every position from the first computed one up to and including the top, so each is filled after its predecessors.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"commonMistakes":["Stopping at the last stair instead of the top","Filling a position before its predecessors are settled"],"hint":"The loop has to reach the top position, one past the last stair.","semanticSpec":{"intent":"Scan the position-indexed state space in increasing order.","doneWhen":"The recurrence iterates over the positions that need a minimum cost.","shouldFailWhen":"This step should fail if the indexed state space is not scanned.","roles":["target position","top position"],"mustProve":["The code scans an indexed state space."],"mustNotAccept":["Handling only a fixed number of positions."]}},{"id":"inner-loop","title":"Consider both jump lengths","description":"For each target position, look at arriving from one position back and from two positions back.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_nested_choice_state_space","scope":"inner-loop","readMode":"dp-value-query-v1"}]},"commonMistakes":["Considering only a one-step arrival","Considering only a two-step arrival"],"hint":"The choices are exactly the two legal jumps: one back and two back.","semanticSpec":{"intent":"For each target position, evaluate both predecessor choices.","doneWhen":"A nested choice loop considers both jump lengths for each position.","shouldFailWhen":"This step should fail if only one predecessor is considered.","roles":["jump length","previous position","target position"],"mustProve":["A nested choice scan exists for the indexed transition."],"mustNotAccept":["A single predecessor update with no alternate choice."]}},{"id":"update-dp","title":"Keep the cheaper arrival","description":"When a predecessor fits, compare the current best with that predecessor cost plus the price of the stair you step off.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"guards_and_writes_min_cost_indexed_transition","scope":"update-dp","readMode":"dp-value-query-v1"}]},"commonMistakes":["Adding the target position price instead of the predecessor stair price","Using max instead of min","Reading a predecessor position that does not exist"],"hint":"Guard that the predecessor fits, then take min(current, predecessor cost + the stair you leave).","semanticSpec":{"intent":"Perform a guarded min-cost transition from a smaller indexed state.","doneWhen":"The current position is updated by a min against a reduced predecessor plus the stair price.","shouldFailWhen":"This step should fail if the predecessor is unchecked, the reduced predecessor is not used, or the update does not keep the cheaper cost.","roles":["current cost","reduced predecessor","stair price","minimum transition"],"mustProve":["The transition is guarded by a fit check.","The write reads a reduced indexed predecessor.","The update keeps the minimum cost."],"mustNotAccept":["A direct overwrite without comparing the current best.","A transition that reads the same index instead of a smaller predecessor."]}},{"id":"return-final-best","title":"Return the top slot","description":"Once every position is filled, the top slot holds the cheapest cost to finish.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-final-best","readMode":"dp-value-query-v1"}]},"commonMistakes":["Returning the last stair slot instead of the top","Returning the smaller raw cost of the last two stairs"],"hint":"Return the table entry for the top position after the loop finishes.","semanticSpec":{"intent":"Return the completed terminal state at the top position.","doneWhen":"The function returns the table value for the top position.","shouldFailWhen":"This step should fail if the returned value is not the terminal state.","roles":["top position","terminal state"],"mustProve":["The return reads the terminal indexed state."],"mustNotAccept":["Returning an intermediate stair's raw input cost."]}}],"slides":[{"id":"the-task","kind":"info","chapter":"The staircase","eyebrow":"Read the problem","title":"Pay to climb, finish past the top","workspacePanel":"problem","body":["Each stair has a price. You start standing before stair 0 or before stair 1, paying nothing yet. From a stair you pay its price, then climb one or two stairs. The finish is the floor just past the last stair.","The obvious way is to recurse: from the top, ask the cheapest way to reach it from one or two positions back. Watch that tree."]},{"id":"brute-force","kind":"code-trace","chapter":"The staircase","eyebrow":"The obvious way","title":"Recurse from the top down","summary":"Asking best(p) from the top down gets every position right, but with no memory it re-asks the same positions again and again. Watch how fast that repeated work piles up.","workspacePanel":"trace","body":["best(p) asks for the cheaper of best(p-1) plus the stair you leave at p-1, and best(p-2) plus the stair at p-2. The recursion keeps no memory, so it re-asks the same positions. A slightly longer four-stair staircase makes the repeated work easy to see, so the tree below traces best(4)."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def minCostClimbingStairs(cost: list[int]) -> int:\n    def best(p: int) -> int:\n        if p <= 1:\n            return 0\n        one = best(p - 1) + cost[p - 1]\n        two = best(p - 2) + cost[p - 2]\n        return min(one, two)\n    return best(len(cost))","steps":[{"id":"fan-out","title":"The call fans out","codeLine":5,"summary":"best(4) asks best(3) and best(2). Each of those asks twice more. The tree below is the full call set for a four-position staircase.","state":{"tree":[4,3,2,2,1,1,0],"node":0}},{"id":"same-position-twice","title":"The same position, asked twice","codeLine":7,"summary":"best(2) is asked twice, once under best(4) and once under best(3), and the recursion recomputes the answer each time.","state":{"tree":[4,3,2,2,1,1,0],"swapped":[2,3]}},{"id":"doubling-levels","title":"Doubling, level by level","codeLine":6,"summary":"Each expanded call fans out into the widening bottom level: every level roughly doubles the calls, about 2^n in total.","state":{"tree":[4,3,2,2,1,1,0],"swapped":[2,3],"visited":[4,5,6]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"function best(p) {\n    if (p <= 1) {\n        return 0;\n    }\n    const one = best((p - 1)) + cost[(p - 1)];\n    const two = best((p - 2)) + cost[(p - 2)];\n    return Math.min(one, two);\n}\nreturn best(cost.length);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":9},"statementBundles":{"4":{"startLine":3,"endLine":4},"7":{"startLine":7,"endLine":8}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"function best(p: number): number {\n    if (p <= 1) {\n        return 0;\n    }\n    const one = best((p - 1)) + cost[(p - 1)];\n    const two = best((p - 2)) + cost[(p - 2)];\n    return Math.min(one, two);\n}\nreturn best(cost.length);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":9},"statementBundles":{"4":{"startLine":3,"endLine":4},"7":{"startLine":7,"endLine":8}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int Best(int p) {\n    if (p <= 1) {\n        return 0;\n    }\n    int one = Best(p - 1) + cost[p - 1];\n    int two = Best(p - 2) + cost[p - 2];\n    return Math.Min(one, two);\n    return 0;\n}\nreturn Best(cost.Count);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"4":{"startLine":3,"endLine":4},"7":{"startLine":7,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int)> best;\n\nbest = [&]( int p ) -> int {\n    if (p <= 1) {\n        return 0;\n    }\n    int one = best((p - 1)) + cost[(p - 1)];\n    int two = best((p - 2)) + cost[(p - 2)];\n    return min(one, two);\n};\nreturn best(cost.size());","lineMap":{"3":4,"4":5,"5":7,"6":8,"7":9,"8":11},"statementBundles":{"4":{"startLine":5,"endLine":6},"7":{"startLine":9,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int best(int p, List<Integer> cost) {\n    if (p <= 1) {\n        return 0;\n    }\n    int one = best((p - 1), cost) + cost.get(p - 1);\n    int two = best((p - 2), cost) + cost.get(p - 2);\n    return Math.min(one, two);\n}\n\nreturn best(cost.size(), cost);","lineMap":{"3":2,"4":3,"5":5,"6":6,"7":7,"8":10},"statementBundles":{"4":{"startLine":3,"endLine":4},"7":{"startLine":7,"endLine":8}}}}}},{"id":"repeated-work-probe","kind":"case-probe","chapter":"The staircase","eyebrow":"Name the waste","title":"How many distinct positions get asked about?","workspacePanel":"trace","options":[{"id":"one-per-position","label":"One question per position: best(0) through best(4), and every other call repeats one of those","rationale":"The position is the entire question. best(2) returns the same cheapest cost wherever it is asked, so exponential calls answer only a handful of distinct questions.","isCorrect":true},{"id":"all-distinct","label":"Seven, one for each call in the tree","rationale":"A call's place in the tree changes nothing about its answer. best(2) is the same question under best(4) as under best(3).","isCorrect":false},{"id":"only-base","label":"Two, the base positions where the cost is zero","rationale":"The base positions seed the answers, but best(2), best(3), and best(4) are each real questions with a cost to derive.","isCorrect":false}],"answer":"One question per position, each with one fixed answer. Solve each once, in an order where its predecessors are ready, and the exponential tree collapses to a single pass.","summary":"The tree for best(4) makes seven calls and grows exponentially with the staircase length."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The rule","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"tree":[4,3,2,2,1,1,0],"swapped":[2,3]}}]}},{"id":"state-meaning","kind":"case-probe","chapter":"The idea","eyebrow":"Define the table","title":"What does dp[p] represent?","summary":"Position 2 is the landing spot after leaving stair 0 or stair 1.","workspacePanel":"trace","options":[{"id":"cost-to-stand","label":"The cheapest cost paid to stand at position p","rationale":"Each position stores the cheapest accumulated cost before taking any later jump from that position.","isCorrect":true},{"id":"stair-price","label":"The price printed on stair p","rationale":"The input array already stores stair prices. dp[p] stores an accumulated cost."},{"id":"jump-count","label":"The number of jumps needed to reach p","rationale":"The problem minimizes paid cost, not jump count."}],"answer":"dp[p] is the cheapest accumulated cost to stand at position p."},{"id":"base-case","kind":"case-probe","chapter":"The idea","eyebrow":"Seed the starts","title":"What cost is paid before standing at position 0 or 1?","summary":"You may start on stair 0 or stair 1.","workspacePanel":"trace","options":[{"id":"zero","label":"Zero for both starts","rationale":"The cost is paid when leaving a stair, so standing at either allowed start has paid nothing yet.","isCorrect":true},{"id":"cost-array","label":"cost[0] and cost[1]","rationale":"Those prices are paid when you step away from the stair, not before the starting position is chosen."},{"id":"min-start","label":"Only the cheaper start gets zero","rationale":"Both starts are allowed. The recurrence will choose the cheaper route later."}],"answer":"dp[0] and dp[1] start at 0 because no stair has been left yet."},{"id":"which-cost-probe","kind":"case-probe","chapter":"The rule","eyebrow":"Find the rule","title":"Jumping from stair 0 to position 2, whose price do you pay?","workspacePanel":"visualizer","summary":"You are arriving at position 2 by leaving stair 0.","options":[{"id":"predecessor","label":"cost[0], the stair you step off","rationale":"You pay for a stair when you stand on it and push off. Arriving from stair 0 means you paid cost[0]; the place you land is not itself paid for here.","isCorrect":true},{"id":"arrival","label":"cost[2], the position you land on","rationale":"You pay cost[p-1] or cost[p-2] for the stair you leave. Position 2 might even be the top, which is past the stairs and has no price at all.","isCorrect":false},{"id":"both","label":"Both, cost[0] plus cost[2]","rationale":"A single move pays for the single stair you push off. The destination is charged only when you later push off it.","isCorrect":false}],"answer":"cost[0], the stair you leave. So arriving at position p from p-1 costs dp[p-1] + cost[p-1], and from p-2 costs dp[p-2] + cost[p-2].","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pay-predecessor","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[0]},{"label":"dp","values":[0,0,"inf","inf"],"changed":[]}],"i":0}}]}},{"id":"recurrence-probe","kind":"case-probe","chapter":"The rule","eyebrow":"Find the rule","title":"What is the cheapest cost to stand at position 2?","workspacePanel":"visualizer","summary":"Position 2 is reached only from stair 0 or stair 1, both already solved at zero.","options":[{"id":"min-of-two","label":"10: the cheaper of arriving from stair 0 (pay 10) and from stair 1 (pay 15)","rationale":"Position 2 has exactly two arrivals, from one or two positions back. The cheapest cost to stand there is the smaller of those two paid arrivals, so 10.","isCorrect":true},{"id":"sum-of-two","label":"25: add both arrivals, 10 + 15","rationale":"You take one route to a position. The two arrivals are alternatives to choose between, so you keep the minimum.","isCorrect":false},{"id":"last-only","label":"15: a position is always reached from the stair right before it","rationale":"A two-stair jump from stair 0 is legal and here it is cheaper at 10, so the one-position-back arrival is not always the answer.","isCorrect":false}],"answer":"min(dp[0] + cost[0], dp[1] + cost[1]) = min(10, 15) = 10. The cheapest cost at a position is the smaller of its two arrivals.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"reach-2","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[]},{"label":"dp","values":[0,0,"inf","inf"],"changed":[]}],"i":2}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it fill","title":"The table fills left to right","workspacePanel":"visualizer","body":["The two starts seed at zero: standing before stair 0 or before stair 1 costs nothing. Every later slot is the cheaper of its two arrivals.","Watch dp fill across cost = [10, 15, 20]: position 2, then the top, each taking the smaller paid arrival."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seeded","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[]},{"label":"dp","values":[0,0,"inf","inf"],"changed":[]}],"i":1}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Fill the table","title":"Trace cost = [10, 15, 20]","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"reach-2","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[0,1]},{"label":"dp","values":[0,0,10,"inf"],"changed":[2]}],"i":2}},{"id":"reach-top","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[1,2]},{"label":"dp","values":[0,0,10,15],"changed":[3]}],"i":3}},{"id":"finished","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[]},{"label":"dp","values":[0,0,10,15],"changed":[3]}],"i":3}}]},"beats":[{"id":"reach-2","title":"Position 2 takes which arrival, 10 or 15?","summary":"Both starts are settled at zero; position 2 is the first computed slot.","prompt":"From stair 0 a two-jump pays cost[0] = 10; from stair 1 a one-step pays cost[1] = 15.","options":[{"id":"ten","label":"10, arriving from stair 0","rationale":"dp[0] + cost[0] = 0 + 10 beats dp[1] + cost[1] = 0 + 15, so the cheaper arrival at position 2 is 10.","isCorrect":true},{"id":"fifteen","label":"15, arriving from stair 1","rationale":"Arriving from stair 1 costs 15, but the two-jump from stair 0 costs only 10, and the min keeps the smaller.","isCorrect":false},{"id":"twentyfive","label":"25, both arrivals added","rationale":"You take one route, not both. The two arrivals are alternatives, so the slot keeps their minimum.","isCorrect":false}],"answer":"dp[2] = min(0 + 10, 0 + 15) = 10. The cheaper arrival comes from stair 0."},{"id":"reach-top","title":"The top takes which arrival, 30 or 15?","summary":"dp now holds 0, 0, 10 for the ground, the two starts, and position 2.","prompt":"From stair 2 the top pays dp[2] + cost[2] = 10 + 20; from stair 1 it pays dp[1] + cost[1] = 0 + 15.","options":[{"id":"fifteen","label":"15, arriving from stair 1 and skipping stair 2","rationale":"dp[1] + cost[1] = 0 + 15 beats dp[2] + cost[2] = 10 + 20 = 30, so the cheapest finish jumps over the costly stair 2.","isCorrect":true},{"id":"thirty","label":"30, arriving from stair 2","rationale":"Stepping off stair 2 costs 30 to finish, but the two-jump from stair 1 costs only 15, and the min keeps it.","isCorrect":false},{"id":"ten","label":"10, carried up unchanged from position 2","rationale":"Reaching the top still pays for the stair you leave, so dp[2] = 10 is not the finish cost; the arrivals are 30 and 15.","isCorrect":false}],"answer":"dp[top] = min(0 + 15, 10 + 20) = 15. The cheaper arrival skips stair 2 entirely."},{"id":"finished","title":"Which slot answers after the table is full?","summary":"dp holds 0, 0, 10, 15 for the ground, two starts, position 2, and the top.","prompt":"The top is the floor past the last stair; the last stair is position 2.","options":[{"id":"top","label":"dp[top] = 15","rationale":"The finish is past the stairs, so the answer is the top slot. Returning dp[2] = 10 would leave you stranded on stair 2, never finishing.","isCorrect":true},{"id":"last-stair","label":"dp[2] = 10, the last stair","rationale":"dp[2] is only the cost to stand on stair 2, not to finish. From there you still must pay cost[2] to leave.","isCorrect":false},{"id":"min-of-stairs","label":"The smaller raw cost, 10 from stair 0","rationale":"The answer comes from the table value at the top slot. Here that cheapest finish is 15.","isCorrect":false}],"answer":"dp[top] = 15. The finish is past the stairs, so the top slot is the answer."}]},{"id":"pay-arrival-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Could you take the more expensive arrival?","workspacePanel":"trace","summary":"Two arrivals reach each position. Swapping the min for a max keeps the same sentinel-filled table and the same loop, and it still compiles and runs. The question is what that one swapped operator does to a slot whose only competition so far is the unsolved sentinel. Watch position 2.","pitfall":"The code below keeps the sentinel-initialized table but combines each slot with its arrivals using max instead of min.","whyItMatters":"min discards the sentinel the moment a real arrival appears; max keeps it, because the sentinel is the largest value around. So every slot freezes at the sentinel and the top returns 3001 instead of the cheapest finish, 15. The fix is min, not max.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def minCostClimbingStairs(cost: list[int]) -> int:\n    n = len(cost)\n    dp = [3001] * (n + 1)\n    dp[0] = 0\n    dp[1] = 0\n    for step in range(2, n + 1):\n        for jump in [1, 2]:\n            cand = dp[step - jump] + cost[step - jump]\n            dp[step] = max(dp[step], cand)\n    return dp[n]","steps":[{"id":"seeded","title":"Sentinel table, both starts at zero","codeLine":5,"summary":"Unsolved slots hold the sentinel 3001 (larger than any real route); only the two starts are seeded to 0.","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[]},{"label":"dp","values":[0,0,3001,3001],"changed":[]}],"i":1}},{"id":"sentinel-sticks-2","title":"Position 2 keeps its sentinel","codeLine":9,"summary":"The real arrivals are 0 + 10 and 0 + 15. But max compares them against dp[2] = 3001, and 3001 is larger, so the sentinel wins and dp[2] stays 3001 instead of becoming 10.","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[0,1]},{"label":"dp","values":[0,0,3001,3001],"changed":[2]}],"i":2}},{"id":"wrong-top","title":"The top returns the sentinel","codeLine":9,"summary":"Every later slot inherits the stuck sentinel, so the top's max ends at 3001. The function returns a placeholder, never the cheapest finish of 15.","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[1,2]},{"label":"dp","values":[0,0,3001,3001],"changed":[3]}],"i":3}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const n = cost.length;\nconst dp = Array((n + 1)).fill(3001);\ndp[0] = 0;\ndp[1] = 0;\nfor (let step = 2; step < (n + 1); step++) {\n    for (const jump of [1, 2]) {\n        const cand = dp[(step - jump)] + cost[(step - jump)];\n        dp[step] = Math.max(dp[step], cand);\n    }\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11},"statementBundles":{"9":{"startLine":8,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const n = cost.length;\nconst dp = Array((n + 1)).fill(3001);\ndp[0] = 0;\ndp[1] = 0;\nfor (let step = 2; step < (n + 1); step++) {\n    for (const jump of [1, 2]) {\n        const cand = dp[(step - jump)] + cost[(step - jump)];\n        dp[step] = Math.max(dp[step], cand);\n    }\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11},"statementBundles":{"9":{"startLine":8,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int n = cost.size();\nList<Integer> dp = new ArrayList<>();\nfor (int index = 0; index < (n + 1); index++) {\n    dp.add(3001);\n}\ndp.set(0, 0);\ndp.set(1, 0);\nfor (int step = 2; step < (n + 1); step++) {\n    for (Integer jump : new ArrayList<>(List.of(1, 2))) {\n        int cand = dp.get(step - jump) + cost.get(step - jump);\n        dp.set(step, Math.max(dp.get(step), cand));\n    }\n}\nreturn dp.get(n);","lineMap":{"2":1,"3":2,"4":6,"5":7,"6":8,"7":9,"8":10,"9":11,"10":14},"statementBundles":{"3":{"startLine":2,"endLine":5},"9":{"startLine":11,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int n = cost.Count;\nList<int> dp = Enumerable.Repeat<int>(3001, n + 1).ToList();\ndp[0] = 0;\ndp[1] = 0;\nfor (int step = 2; step < n + 1; step++) {\n    foreach (int jump in new List<int> { 1, 2 }) {\n        int cand = dp[step - jump] + cost[step - jump];\n        dp[step] = Math.Max(dp[step], cand);\n    }\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11},"statementBundles":{"9":{"startLine":8,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int n = cost.size();\nvector<int> dp = vector<int>((n + 1), 3001);\ndp[0] = 0;\ndp[1] = 0;\nfor (int step = 2; step < (n + 1); step++) {\n    for (int jump : vector<int>{1, 2}) {\n        int cand = dp[(step - jump)] + cost[(step - jump)];\n        dp[step] = max(dp[step], cand);\n    }\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11},"statementBundles":{"9":{"startLine":8,"endLine":10}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","ctaLabel":"Check edge cases","workspacePanel":"visualizer","body":["Two inputs press on the recurrence. The first is the smallest possible staircase, cost = [1, 2], where the top is one jump from a start and nothing computes in between.","The second is an alternating staircase with a cheap last stair, cost = [10, 1, 10, 1, 10, 1], where the last stair is tempting to read as the answer. Each probe puts one of these under the rule."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[]},{"label":"dp","values":[0,0,10,15],"changed":[3]}],"i":3}}]}},{"id":"two-stairs-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Force a decision","title":"With cost = [1, 2], what is the cheapest finish?","workspacePanel":"visualizer","summary":"This is the smallest allowed staircase.","options":[{"id":"one","label":"1, by starting on stair 0 and jumping two","rationale":"Both starts seed at zero, so the top takes min(dp[0] + cost[0], dp[1] + cost[1]) = min(1, 2) = 1. The two seeded starts make stair 0 a legal finish.","isCorrect":true},{"id":"two","label":"2, because stair 0 is mandatory before stair 1","rationale":"Starting on stair 1 is legal, and so is jumping two off stair 0; the cheaper of those is 1, so stair 0 is not forced.","isCorrect":false},{"id":"three","label":"3, paying for both stairs","rationale":"You never step on both stairs to finish two of them; one jump off a single start clears the staircase.","isCorrect":false}],"answer":"1. With both starts seeded at zero, the top takes min(1, 2) and the single jump off stair 0 wins.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-stairs","state":{"rows":[{"label":"cost","values":[1,2]},{"label":"dp","values":[0,0,1],"changed":[2]}],"i":2}}]}},{"id":"skip-last-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Force a decision","title":"On cost = [10, 1, 10, 1, 10, 1], which slot is the answer?","workspacePanel":"visualizer","summary":"The last stair is cheap, and the last two table slots are close.","options":[{"id":"top","label":"The top slot, dp[6] = 3","rationale":"The finish is the floor past the last stair, so the answer is dp[6] = 3. Reaching it pays for one more stepped-off stair than just standing on stair 5.","isCorrect":true},{"id":"last","label":"The last stair slot, dp[5] = 2","rationale":"dp[5] = 2 only pays to stand on stair 5; finishing from there still costs cost[5] = 1 more, so it underreports the real finish of 3.","isCorrect":false},{"id":"min-both","label":"The smaller of the last two stair slots, dp[4] = 2","rationale":"The top slot already chose the cheaper arrival into the finish.","isCorrect":false}],"answer":"dp[6] = 3. The top slot is one past the last stair; returning dp[5] = 2 would forget the cost of stepping off stair 5 to finish.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"skip-last","state":{"rows":[{"label":"cost","values":[10,1,10,1,10,1],"changed":[]},{"label":"dp","values":[0,0,1,1,2,2,3],"changed":[6]}],"i":6}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The min is over two arrivals; the price is the stair you leave.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["Build a table with one slot per position through the top, seed both starts at zero, then walk each position taking the cheaper of its two arrivals and returning the top slot.","Each arrival pays for the stair you step off, and the answer is the top slot past the last stair."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready","state":{"rows":[{"label":"cost","values":[10,15,20],"changed":[]},{"label":"dp","values":[0,0,"inf","inf"],"changed":[]}],"i":1}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the cost table","summary":"Now turn the rule into code: size the table through the top and fill it with a sentinel, seed both starts at zero, then walk each position, weigh both jump lengths, keep the cheaper guarded arrival, and return the top slot.","workspacePanel":"code"},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["Min Cost Climbing Stairs is the same 1D skeleton as counting routes, with two twists: you minimize instead of count, and each transition carries the price of the stair you leave.","Exponentially many climbs collapse to one question per position, and the answer is read from the floor past the last stair."],"takeaways":[{"title":"Decompose by the last arrival","body":"A position is reached only from one or two positions back, so dp[p] = min(dp[p-1] + cost[p-1], dp[p-2] + cost[p-2])."},{"title":"Charge the stair you leave","body":"A move pays for the stair you push off. The top has no stair cost of its own, but reaching it still costs the move that leaves stair n-1 or n-2."},{"title":"The answer is past the stairs","body":"The finish is the slot one beyond the last stair, so returning the last stair slot can strand you on a stair you still owe for."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
