Practice
Solution
Step 1: Understand the problem constraints
The problem requires finding the cheapest flight with at most K stops, which limits path length and requires considering multiple paths.Step 2: Identify suitable algorithm
Greedy Dijkstra fails because it doesn't limit stops; DFS is exponential; topological sort requires DAG which flights graph may not be. Bottom-up DP iterates over stops and relaxes edges, guaranteeing optimal cost within K stops.Final Answer:
Option D -> Option DQuick Check:
Bottom-up DP with stops limit ensures optimal solution [OK]
- Using Dijkstra without stop limit
- Trying DFS without pruning
- Assuming DAG for topological sort
grid = [
[0, 1, -1],
[1, 0, -1],
[1, 1, 1]
]
from typing import List
def cherryPickup(grid: List[List[int]]) -> int:
n = len(grid)
dp = [[[-float('inf')] * n for _ in range(n)] for __ in range(n)]
dp[0][0][0] = grid[0][0]
for step in range(1, 2 * (n - 1) + 1):
for r1 in range(max(0, step - (n - 1)), min(n, step + 1)):
c1 = step - r1
if c1 < 0 or c1 >= n:
continue
for r2 in range(max(0, step - (n - 1)), min(n, step + 1)):
c2 = step - r2
if c2 < 0 or c2 >= n:
continue
if grid[r1][c1] == -1 or grid[r2][c2] == -1:
continue
candidates = []
if r1 > 0 and r2 > 0:
candidates.append(dp[r1 - 1][c1][r2 - 1])
if r1 > 0 and c2 > 0:
candidates.append(dp[r1 - 1][c1][r2])
if c1 > 0 and r2 > 0:
candidates.append(dp[r1][c1 - 1][r2 - 1])
if c1 > 0 and c2 > 0:
candidates.append(dp[r1][c1 - 1][r2])
best_prev = max(candidates) if candidates else -float('inf')
if best_prev == -float('inf'):
continue
val = best_prev + grid[r1][c1]
if r1 != r2:
val += grid[r2][c2]
dp[r1][c1][r2] = max(dp[r1][c1][r2], val)
return max(0, dp[n - 1][n - 1][n - 1])
print(cherryPickup(grid))
Solution
Step 1: Trace dp states for step=4 (final step for 3x3 grid)
At step=4, both players reach bottom-right (2,2). The dp value dp[2][2][2] accumulates max cherries collected along valid paths avoiding thorns (-1).Step 2: Calculate max cherries collected
By tracing paths, max cherries collected is 6, considering both players' paths and avoiding double counting.Final Answer:
Option A -> Option AQuick Check:
Manual path tracing confirms max cherries = 6 [OK]
- Off-by-one errors in step or indices
- Double counting cherries when players overlap
- Ignoring thorn cells leading to invalid paths
Solution
Step 1: Understand problem constraints
The problem requires minimizing turns to print a string where each turn prints a continuous block of identical characters.Step 2: Identify suitable algorithmic pattern
Greedy or sliding window approaches fail to merge overlapping prints optimally. Pure recursion is inefficient. Interval DP with string compression and merging states captures overlapping subproblems and optimizes turns.Final Answer:
Option A -> Option AQuick Check:
Interval DP with compression is known optimal [OK]
- Assuming greedy printing each char separately is optimal
n vertices?Solution
Step 1: Identify loops in the code
There are three nested loops: length (up to n), i (up to n), and k (up to n), each iterating up to n times.Step 2: Calculate total complexity
Multiplying these loops gives O(n * n * n) = O(n^3). No extra log factor or higher power arises.Final Answer:
Option C -> Option CQuick Check:
Three nested loops over n vertices -> cubic time [OK]
- Confusing recursion stack space
- Assuming only two nested loops
- Adding unnecessary log factors
m x n grid using a space-optimized DP approach:def uniquePaths(m, n):
dp = [1] * n
for i in range(1, m):
for j in range(1, n):
dp[j] = dp[j] + dp[j]
return dp[-1]What is the bug in this code?Solution
Step 1: Analyze inner loop update
Line 4 updates dp[j] by adding dp[j] to itself, doubling the value instead of adding dp[j-1].Step 2: Identify correct update
The correct update is dp[j] += dp[j - 1] to accumulate paths from left and top cells.Final Answer:
Option B -> Option BQuick Check:
Doubling dp[j] breaks path count logic -> bug at line 4 [OK]
- Using dp[j] + dp[j] instead of dp[j] + dp[j-1]
- Off-by-one errors in loops
