Memoization (Top-Down)
PremiumRemember each answer once, and the call tree collapses.
O(n) time · O(n) spaceVisualizeLearn memoization and tabulation with classic DP problems.
2 algorithms2 races7 problems
2 algorithms. Each one builds on the last.
Remember each answer once, and the call tree collapses.
O(n) time · O(n) spaceVisualizeFill a table of best values for every item and capacity.
O(n · W) time · O(n · W) spaceVisualizeSame input, side by side. Watch who wins.
Dynamic programming solves a problem by solving smaller versions of it first and saving each answer, so no smaller question is worked out twice. It applies when the best answer to the whole is built from best answers to its parts, and those parts overlap. It is among the most tested interview topics, and it runs inside diff tools and DNA alignment.
Each page defines a state, such as the best value from the first i items under a weight limit w, writes how one state follows from smaller ones, and stores the answers in a memo or a table so each is computed once. That is what turns trying every combination, which grows exponentially, into work that grows with the number of states and the choices at each one.
Name the state first, then pick the method: memoize the recursion as the Fibonacci page does, or fill a table in a loop when every state is needed anyway, which also avoids deep recursion. Watch one classic mix-up: a subsequence may skip items, as in LCS and LIS, while a subarray may not, as in Kadane.