KatInterview

Sliding Block Minimums and Dependency-Ordered Cooking Plan

Trees & GraphsModel answer
MediumModel answerTrees & Graphstopological-sortmonotonic-dequesliding-window

Last 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.