Sliding Block Minimums and Dependency-Ordered Cooking Plan
Trees & GraphsModel answerLast updated
Compute the minimum of every K x K window in a grid, then order recipes so that every derived ingredient is made before the dish that uses it, detecting cycles.
This exercise has two independent parts.
Part 1: Smallest value in every square window
You get an integer matrix with M rows and N columns, plus a window size K. For every position where a K x K square fits entirely inside the matrix, find the smallest number in that square. Return an (M-K+1) x (N-K+1) matrix where entry [i][j] is the minimum of the square whose top-left corner is (i, j).
Constraints: 1 <= K <= min(M, N) and M, N <= 1000. Your solution should be clearly faster than the brute-force O(M * N * K^2).
Part 2: Ordering recipes by their dependencies
You are given a dictionary that maps each recipe name to the list of ingredients it needs. An ingredient is either:
- a base item that is not a key in the dictionary and is always available, or
- a derived item that is a key in the dictionary and must be prepared before any recipe that uses it.
Write a function that returns a valid preparation order containing every recipe (keys only, never base items). If the dependencies contain a cycle, so that no valid order exists, return an empty list.
def get_preparation_order(recipes: dict[str, list[str]]) -> list[str]:
...
Example input:
{
"Cake": ["Flour", "Frosting"],
"Frosting": ["Sugar", "Butter"],
"Flour": []
}
Here Sugar and Butter are base items. Flour is a recipe with no ingredients. A valid answer is ["Flour", "Frosting", "Cake"]; any order in which Cake comes after both Flour and Frosting is accepted.
Cases to handle:
- An empty dictionary.
- Several unrelated groups of recipes.
- Cycles, including a recipe that lists itself.
- An ingredient repeated within one recipe's list.
What to cover in your answer: the approach for each part, why it is correct, time and space complexity, and working code.
Hints
Hint 1
For Part 1, a minimum over a rectangle can be computed in two stages: first collapse each row into window minimums of width K, then collapse the columns of that intermediate result with height K.
Hint 2
A one-dimensional sliding-window minimum can be done in linear time with a deque of indices. Keep the values in it increasing, drop indices from the back that are no larger than the new value, and drop from the front once an index leaves the window.
Hint 3
For Part 2, treat recipe names as graph nodes and draw an edge from each derived ingredient to the recipe that uses it. Ignore base items, remove duplicate ingredients in a list, and repeatedly emit recipes that have no unprepared dependencies left. If you cannot emit all recipes, there is a cycle.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
Each part reduces to a standard technique. Part 1 becomes two passes of a one-dimensional sliding-window minimum. Part 2 is a topological sort with cycle detection.
Part 1: Window minimums over a grid
Approach
Taking the minimum is associative and commutative, so a K x K minimum can be split into two one-dimensional steps:
- Row pass. For each row, compute the minimum of every run of
Kconsecutive cells. This gives anM x (N-K+1)intermediate grid. - Column pass. For each column of the intermediate grid, compute the minimum of every run of
Kconsecutive cells. This gives the final(M-K+1) x (N-K+1)result.
The minimum of a block is the minimum over its K rows of each row's minimum across the block's columns, which is exactly what the two passes compute.
The one-dimensional step
Use a deque that stores indices, with the values at those indices increasing from front to back. For each new index i:
- Pop from the back while the value there is
>=the new value. Those entries are dominated: the new value is no larger and stays in the window longer. - Push
i. - Pop from the front while the front index is
<= i - K, because it has left the window. - Once
i >= K - 1, the front of the deque holds the window minimum.
Every index is pushed once and popped at most once, so each pass is linear.
Complexity
- Time:
O(M * N). Brute force isO(M * N * K^2), and optimizing only one dimension still costsO(M * N * K). - Space:
O(M * N)for the intermediate grid and the output, plusO(K)for the deque.
Edge cases
K = 1returns the input unchanged.K = M = Nreturns a single cell.- Duplicates are fine, since popping on
>=or>both work. - Negative values need no special handling.
Part 2: Recipe ordering
Approach
Build a directed graph:
- Nodes: only the dictionary keys. Base items are assumed to be on hand and never appear in the output.
- Edges: for each ingredient that is itself a key, add an edge from that ingredient to the recipe using it.
Then run Kahn's algorithm:
- Compute each recipe's in-degree, meaning how many distinct derived ingredients it needs.
- Put every recipe with in-degree 0 in a queue.
- Pop a recipe, append it to the order, and decrement the in-degree of everything that depends on it. Enqueue any recipe that hits 0.
- If the order has fewer entries than there are recipes, the leftovers are on or behind a cycle, so return
[].
Why it works
A recipe is emitted only when all of its derived ingredients were already emitted, so the order is valid. Any node on a cycle always has at least one unemitted predecessor, so it can never reach in-degree 0. The length check therefore detects cycles exactly.
Complexity
- Time:
O(R + E), withRrecipes andEthe total length of all ingredient lists. - Space:
O(R + E).
Edge cases
- Empty input: return
[]. - Independent groups: every source is seeded at the start, so they are handled naturally.
- Self-reference (
"A": ["A"]): the recipe is its own prerequisite, so it is a cycle and the answer is[]. - Repeated ingredient (
["Flour", "Flour"]): deduplicate per recipe. Otherwise the in-degree would count an edge that the adjacency list may not match, leading to wrong results. - Multiple valid orders: any is acceptable. The code below returns
["Frosting", "Flour", "Cake"]for the sample, which is equally valid.
Code
from collections import deque
def sliding_min(arr, k):
"""Minimum of every length-k window of arr in O(len(arr))."""
dq = deque() # indices; values increasing from front to back
out = []
for i, x in enumerate(arr):
while dq and arr[dq[-1]] >= x:
dq.pop()
dq.append(i)
if dq[0] <= i - k: # front left the window
dq.popleft()
if i >= k - 1:
out.append(arr[dq[0]])
return out
def grid_block_minima(grid, k):
if not grid or not grid[0]:
return []
horiz = [sliding_min(row, k) for row in grid] # M x (N-K+1)
cols = [sliding_min(list(c), k) for c in zip(*horiz)] # per column
return [list(r) for r in zip(*cols)] # (M-K+1) x (N-K+1)
def get_preparation_order(recipes):
if not recipes:
return []
indegree = {r: 0 for r in recipes}
dependents = {r: [] for r in recipes}
for recipe, ingredients in recipes.items():
for ing in dict.fromkeys(ingredients): # dedupe, keep order
if ing in recipes: # skip base items
dependents[ing].append(recipe)
indegree[recipe] += 1
queue = deque(r for r in recipes if indegree[r] == 0)
order = []
while queue:
cur = queue.popleft()
order.append(cur)
for nxt in dependents[cur]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
return order if len(order) == len(recipes) else []
Common mistakes
- Running the brute-force scan over each block, or optimizing only one dimension.
- Forgetting to expire the front of the deque, which lets stale minimums leak into later windows.
- Emitting a result before the first full window (
i < K - 1). - Adding base items to the graph or to the output.
- Not deduplicating ingredients, which corrupts in-degree counts.
- Returning a partial order when a cycle exists instead of an empty list.
Likely follow-ups
- Limited number of stations
C: run Kahn's algorithm in rounds, taking up toCready recipes each round. Minimizing rounds is NP-hard in general, so use a heuristic that prefers recipes with the longest remaining chain to the end (critical-path-first). It is optimal for tree-shaped dependencies. With different durations, use event-driven scheduling with a min-heap of finish times. - Grid values that change: recompute only the affected rows and the affected columns of the intermediate grid for a point update, or use a 2D sparse table (
O(MN log^2)build,O(1)query) if the grid is static and queries vary in size.