Choose an approach without the label
For each prompt, write: the requested output, a state sentence, legal transitions, the property your approach relies on, a cost estimate, and one counterexample to a tempting alternative. Do this before opening the answer. A correct alternative with an honest cost bound is welcome.
Use three prompts per session. On later reviews, keep the structure but change the story or constraint. Explaining why the old solution stops working is part of the exercise.
1. Elevator buttons
Floors are 0..30. A press moves up 4 or down 3, staying in bounds. Find the fewest presses from 2 to 19. Then change the buttons so an upward press costs 5 seconds and a downward press costs 1 second; minimize time instead.
Hint
What is a vertex, and what quantity should order the unfinished work?
Reasoning and check
The floor is sufficient state under fixed button rules. BFS solves fewest presses; there are 31 vertices and at most two outgoing moves each. The first answer is six presses: five ups and one down, ordered to stay in bounds. With different nonnegative time costs, Dijkstra is a valid general approach. In this particular input the same move counts also minimize time, but BFS’s usual proof does not establish that for arbitrary weighted transitions. See BFS and Dijkstra.
2. Study days
Each practice session has a predicted benefit: [4,5,4]. You cannot attend adjacent sessions. Maximize benefit, allowing no sessions. Then require at least one session and consider [-4,-2].
Hint
What remains after taking the current session? What did a zero base case permit?
Reasoning and check
Compare skip best(i+1) with take benefit[i]+best(i+2). One suffix index suffices, with O(n) states and constant work each. The first result is 8. For the nonempty negative case, the answer is -2; the original empty-allowed recurrence would incorrectly return zero. Enforce nonempty feasibility through state or an appropriate reformulation. See 1D DP.
3. Emergency passage
On a board you can move in four directions. You may remove one wall. Find the fewest moves to the exit. Two routes reach the same square with different remaining wall-removal budgets.
Hint
Does the original board location determine legal next moves? Does movement impose a DAG?
Reasoning and check
Use BFS over (row,column,budget_left), with discovered state including the budget. The expanded graph has O(RC(K+1)) states and bounded outdegree for general budget K. Four-direction cycles invalidate the unchanged right/down DP recurrence. More remaining budget can sometimes support a carefully proved dominance optimization, but do not discard that coordinate without one. See state and budget DP.
4. Cable distance
A connected acyclic network has one unweighted cable per edge. Find the largest number of edges on a simple route between any two devices. The route need not contain the device chosen as root.
Hint
Which branch information should go upward, and which two-branch candidate can you measure at a node?
Reasoning and check
Root the tree, compute downward heights, and combine the best two child branches at every node. Retain the maximum candidate across nodes. O(V) time; stack O(h). In an adjacency-list tree, skip the parent edge. Returning a diameter as though it were a single extendable height is a common wrong combination. See diameter.
5. Search suggestions
A fixed dictionary receives many prefix queries and returns all completions. A revised product instead asks only whether an exact word exists.
Hint
What relationship does each query use, and how much output must it produce?
Reasoning and check
A trie shares prefix work and then traverses a matching subtree. A set may be sufficient for the exact-membership workload. Neither bypasses string hashing/comparison or output costs in a detailed model. A trie end marker distinguishes a word from a prefix. See tries and autocomplete.
6. Build prerequisites
Tasks have durations and directed prerequisites. Unlimited workers can execute independent tasks in parallel. Find the earliest finish time for all work, or report that the prerequisites contain a cycle.
Hint
Readiness supplies an order; what summary travels along dependency edges?
Reasoning and check
Topologically process ready tasks. Earliest finish of a task is its duration plus the maximum predecessor finish, with zero for no predecessor. The total finish is the maximum task finish. Check that every task was processed to detect cycles. Time O(V+E). Summing every duration ignores parallelism. See dependencies.
7. A full box
Given physical items with positive integer weights, count subsets whose total weight is exactly W. Equal weights on different physical items represent distinct choices. Each item may be used once.
Hint
Separate availability from remaining capacity, and define the empty suffix’s answer.
Reasoning and check
Use ways(i,remaining), adding skip and feasible take, both advancing the item index. With no items left, return one only if remaining is zero. A negative remaining capacity is impossible. State bound O(nW), constant transitions each. Value-based deduplication would remove required physical-item choices. See knapsack and coin semantics.
8. Shared reading
Find the longest sequence of characters appearing in order in both texts, allowing gaps. Then change “allowing gaps” to “must be contiguous in both.”
Hint
How many reading positions are independent, and what does a mismatch mean?
Reasoning and check
The first is LCS over two suffix positions with matching or skipping transitions, O(mn) time and space in the basic implementation. The contiguous version needs a different contract, such as matching length ending at (i,j), resetting to zero on mismatch. A two-coordinate shape does not uniquely determine the recurrence. See string DP.
9. Connect the sensors
You can install undirected links between sensors at specified costs. Connect all sensors for minimum total installation cost. Then change the objective to minimizing travel cost from one central sensor to every other sensor.
Hint
Are you paying once for a network, or measuring separate routes?
Reasoning and check
The first calls for an MST when the graph is connected: Kruskal plus disjoint sets is one approach, dominated by sorting edges. The second is a shortest-path problem; Dijkstra fits nonnegative costs. The triangle with costs 2,2,3 distinguishes the results. An MST need not preserve cheapest individual routes. See spanning trees.
10. Spending streak
Find the longest contiguous sequence of daily expenses totaling at most a limit. Then allow refunds, represented as negative expenses.
Hint
Can adding another day repair an over-limit sequence?
Reasoning and check
With nonnegative expenses and limit, a moving sum window has safe monotonic updates and takes O(n) time. Refunds break that justification: [6,-2] under limit 5 is a counterexample. Re-derive a prefix-based approach or use a quadratic baseline for small inputs; the exact-sum frequency trick solves a different objective and cannot be copied unchanged. See windows.
11. Team invitations
Each person has an invitation value. Reporting relationships form a tree. Invite people to maximize total value, but never invite both a person and their direct manager. Then add cross-team conflict edges.
Hint
What choice at the boundary changes which child answer is valid?
Reasoning and check
Return taken/skipped values for each subtree and combine conditionally, O(n) time on a tree. Cross-team edges can couple formerly independent branches, so the same recurrence can become wrong. Do not assume a two-value summary still describes those interactions. See tree DP.
12. Letter paths
Find every dictionary word on a four-neighbor board, without reusing a cell within a word. Then ask for every coordinate path spelling each word.
Hint
Which structure shares possible spellings, and which memory belongs only to the active route?
Reasoning and check
A trie guides a backtracking board search; a path-local visited set prevents repeated cells. A set of found words satisfies the first contract but loses required coordinate paths in the second. Worst-case search remains exponential in useful word length, and output size matters. See board word search.
Check your explanation
Mark each dimension separately: correct state, justified transitions, correct base cases, honest cost, and a meaningful failing variant. A successful code run alone does not prove those explanations. After a delay, retry a prompt from another family without its hint. Use your missing explanation to choose the next card.