Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming

1D / Fibonacci-style

O(n)

Define dp[i] from dp[i−1]/dp[i−2]; usually collapsible to two rolling variables.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksFloyd-Warshall0/1 KnapsackLCS / Two-SequenceLongest Increasing Subsequence+12
0%
mastery
0/58 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Count ways or best value along a line where step i depends on i-1, i-2: stairs, house robber, decode ways, word break, take-or-skip.

  1. 1Brute force

    Plain recursion over choices: exponential.

  2. 2The observation

    Overlapping subproblems: each prefix is solved once.

  3. 3Why it works

    dp[i] is the final answer for the prefix ending at i; once every dp[j] with j < i is known, dp[i] is fully determined.

Reach for it when

  • +The answer at step i depends on a fixed window of earlier steps (i-1, i-2).
  • +'Count the ways' / 'max or min value' along a 1-D sequence — stairs, robbing, decoding, jumps.
  • +You see exponential recursion with overlapping subproblems on a single index.

Not when

  • ×Subproblems don't overlap, each one is uniqueuse Plain recursion / divide & conquer
  • ×No optimal substructure: subresults can't be combined into the answeruse Rethink the model; DP doesn't apply
  • ×State needs a second axis (a second string, capacity) or modesuse 2-D DP: LCS, knapsack, state machine
  • ×A provable greedy exists (jump game)use Greedy
  • ×You think greedy works here: robbing the richest house can forfeit two good neighboursuse max(skip, take + dp[i-2])
  • ×The transition takes the best over a sliding range of earlier statesuse DP + monotonic deque
  • ×It's a contiguous-subarray constraint, not a recurrence over an indexuse Sliding window

Intuition

Dynamic programming sounds scary; it's just "don't solve the same thing twice." If a big problem breaks into smaller versions of itself, and those small versions repeat, you compute each once and reuse the answer.

Read the full intuition

The gateway is Fibonacci. fib(n) = fib(n-1) + fib(n-2). Computed naively it recomputes fib(3) a zillion times — exponential. Two fixes, and DP is always one of them:

  • Memoization (top-down): keep recursion, but cache each answer in a dict; on a repeat, return the cache. Recursion + a memo is DP.
  • Tabulation (bottom-up): make an array dp, fill dp[0], dp[1] (base cases), then loop dp[i] = dp[i-1] + dp[i-2]. No recursion.

To invent a 1D DP, answer three questions:

  1. What does dp[i] mean? ("the answer considering the first i things / ending at i".)
  2. Transition: how does dp[i] build from earlier entries?
  3. Base cases & answer: what are the smallest known values, and which cell is the final answer?

Climbing Stairs (1 or 2 steps at a time): dp[i] = ways to reach step i. To land on i you came from i-1 (one step) or i-2 (two) → dp[i] = dp[i-1] + dp[i-2]. It's literally Fibonacci. House Robber changes only the transition: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) — skip this house, or rob it and add the best up to i-2.

Key idea

When dp[i] only looks back a fixed distance (i-1, i-2), you don't need the whole array — two rolling variables replace it, dropping space to O(1).

Why it costs what it costs

Time O(n). each of n states is computed once in O(1).

Space O(1). only the last one or two dp values are needed; the full array collapses to a couple of variables.

Practice

Next · Foundation

Climbing Stairs

dp[i] = dp[i-1] + dp[i-2]; O(1) space rolling.

0/58 solved
  • Climbing StairsFoundationFoundationAmazon, AdobeEasy
  • Min Cost Climbing StairsApply it · Minimise cost instead of counting.Apply itEasy
  • House RobberOne change · Take/skip with adjacency constraint.One changeMedium
  • House Robber IITwists · Circular array.TwistsMedium
  • Decode WaysTwists · Invalid states ('0', '30').TwistsMedium
  • Delete and EarnBranches · Hidden reduction.BranchesMedium
  • Word BreakBranches · Transition over a set of previous indices.BranchesSnowflake, CitadelMedium
  • Maximum Product SubarrayCombine · Sign flips.CombineAmazon, AdobeMedium
  • Jump Game VIMastery checkMastery checkCitadel, AmazonMedium
  • Fibonacci NumberAdobe, AmazonEasy
  • Ugly Number IIAmazon, AdobeMedium
  • Palindrome Partitioning IIHard

Pitfalls

Classic bugs

  • !Wrong base cases at dp[0]/dp[1] silently shift every answer. Check n = 0, 1, 2 by hand.
  • !Vague state meaning: decide 'ends at i' vs 'best within prefix i' before writing transitions.
  • !Circular (House Robber II): first and last conflict. Run linear DP twice, excluding first then last, take max.
  • !Decode Ways: a standalone or leading '0' has no single-digit decoding; handle '0' and the 10-26 window explicitly.
  • !Rolling variables clobbered by update order: use a temp or tuple assignment.
  • !Mixed operators: 'count ways' sums (+), 'best value' takes max/min.

Looks like it, isn't

  • House Robber III needs DP on Trees
    Why
    Same take/skip idea but on a tree: dp[v] = (take, skip) from children.
  • Jump Game II needs Greedy
    Why
    O(n2) DP works but the greedy BFS over reach windows is O(n).
  • Maximum Subarray needs Kadane's Algorithm
    Why
    It is DP, but the named O(1)-space form is Kadane's algorithm.
  • New 21 Game needs Probability & Expected-Value DP (linearity of expectation)
    Why
    The probability DP over points is O(n*maxPts) unless the transition sum is kept as a sliding window. source ↗
Go deepervariants and techniques · 11 combinations · interviewer follow-ups · resources

Variants and techniques

  • Kadane's Algorithmbest_ending_here = max(x, best_ending_here + x); the answer is the max over all positions.
  • Slope TrickCP 2400+Keep dp(x), a convex piecewise-linear function of a value x, as the multiset of its breakpoints in one or two heaps. Each transition (add |x - a|, take a prefix minimum, shift) then costs O(log n) heap operations instead of a pass over all values.
  • Connected-Component DP (insertion DP)CP 2400+Process elements in sorted order, keeping only how many 'components' (open groups, or partial segments of the final permutation) exist. Each new element starts a component, extends one, or merges two, with counts for each choice.
  • Counting (Fibonacci-shaped)dp[i] sums ways from previous states. Climbing Stairs, Decode Ways.
  • Optimizing (rob/skip)dp[i] = max(skip, take + dp[i-2]). House Robber.
  • CircularRun the linear DP on [0..n-2] and [1..n-1], take the better. House Robber II.
  • Cost minimizationdp[i] = cost[i] + min(dp[i-1], dp[i-2]). Min Cost Climbing Stairs.

Combinations

  • 1D / Fibonacci-style+Monotonic Deque

    jump at most k steps; subsequence with gaps at most k

    1D / Fibonacci-style:
    defines dp[i] from a range of previous states
    Monotonic Deque:
    range max of dp in amortised O(1)

    Jump Game VIConstrained Subsequence Sum

  • Topological Sort+1D / Fibonacci-style

    longest path / number of paths in a DAG; longest increasing path in a grid

    Topological Sort:
    provides an order where predecessors are final
    1D / Fibonacci-style:
    longest/count paths along that order

    Longest Flight RouteGame RoutesLongest Increasing Path in a Matrix

  • Strongly Connected Components & Condensation+Topological Sort+1D / Fibonacci-style

    maximum total collected on a walk in a directed graph with cycles

    Strongly Connected Components & Condensation:
    condenses cycles into super-nodes
    Topological Sort:
    orders the condensation DAG
    1D / Fibonacci-style:
    accumulates values along DAG paths

    Coin Collector

  • Dijkstra (Weighted Shortest Path)+1D / Fibonacci-style

    number of shortest paths; min/max edges among shortest paths

    Dijkstra (Weighted Shortest Path):
    settles vertices in distance order
    1D / Fibonacci-style:
    aggregates counts/min/max edges over shortest paths

    InvestigationNumber of Ways to Arrive at Destination

  • Trie (Prefix Tree)+1D / Fibonacci-style

    word break / count segmentations with a big dictionary

    Trie (Prefix Tree):
    enumerates dictionary words starting at i in one walk
    1D / Fibonacci-style:
    counts/decides segmentations

    Word CombinationsWord Break

  • Palindromic Substrings+1D / Fibonacci-style

    minimum palindrome partition cuts

    Palindromic Substrings:
    O(1) palindrome check for any substring
    1D / Fibonacci-style:
    min cuts over prefixes

    Palindrome Partitioning II

  • Matrix Exponentiation+1D / Fibonacci-style

    count sequences of length n with a fixed small automaton

    Matrix Exponentiation:
    applies it n times in O(k^3 log n)
    1D / Fibonacci-style:
    defines a constant-size linear transition

    Throwing DiceFibonacci Numbers

  • Convex Hull Trick / Li Chao Tree+1D / Fibonacci-style

    cost is product of a term of j and a term of i

    Convex Hull Trick / Li Chao Tree:
    queries the lower envelope of lines
    1D / Fibonacci-style:
    defines dp[i] = min_j (m_j * x_i + b_j) + c_i

    Monster Game IMonster Game IIThe Fair Nut and Rectangles

  • Interval Scheduling (sort by end)+1D / Fibonacci-style+Binary Search

    choose non-overlapping intervals maximising total weight (or at most k of them)

    Interval Scheduling (sort by end):
    sort by end so that compatible predecessors form a prefix
    1D / Fibonacci-style:
    dp[i] = max(dp[i-1], w_i + dp[p(i)])
    Binary Search:
    find the last job ending at or before the current start

    Maximum Profit in Job SchedulingMaximum Number of Events That Can Be Attended IIProjects

  • Slope Trick+Top-K Elements

    minimum total |change| to make an array non-decreasing, with large values

    Slope Trick:
    represent the cost function by its breakpoints
    Top-K Elements:
    a max-heap holds the breakpoints left of the minimum

    Increasing Array IISonya and Problem Wihtout a LegendSequence

  • Probability & Expected-Value DP (linearity of expectation)+1D / Fibonacci-style+Sliding Window

    probability over a running total with uniform draws and a stopping threshold

    Probability & Expected-Value DP (linearity of expectation):
    P(i) = (1/W) * sum of P(i - k) over k = 1..W
    1D / Fibonacci-style:
    the probability DP over points
    Sliding Window:
    keep that sum in O(1) per step

    New 21 Game

Follow-ups interviewers ask

  1. 01Can you drop the array to O(1) space? → yes when dp[i] looks back a fixed distance — keep two rolling variables.
  2. 02What if the array is circular (first and last conflict)? → run the linear DP twice (exclude first, exclude last) and take the max.
  3. 03Need the actual choices, not just the value? → store parent pointers / reconstruct by walking the dp backward.
  4. 04Transition depends on the last k states, not 1–2? → maintain a windowed max with a monotonic deque (O(n)).

State table

i nums[i] dp[i-2]+nums[i] (rob) dp[i-1] (skip) dp[i] = max
0 2 — — 2
1 7 — 2 7
2 9 2+9=11 7 11
3 3 7+3=10 11 11
4 1 11+1=12 11 12

Resources

  • DP lecture notesErrichto · video
  • AtCoder Educational DP ContestAtCoder · sheet
  • Introduction to DPUSACO Guide · course
  • Dynamic Programming PatternsLeetCode discuss · article
  • Dynamic Programming playlistAditya Verma · video
  • Bitmask DPUSACO Guide · course
  • Digit DPCodeforces · blog
Minimum Spanning Tree0/1 Knapsack
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial