Solve matrix groups and recipe inventory
GoogleSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to manage hierarchical dependencies using topological sorting and perform block-wise aggregate computations on grid-based data structures.
Part 1: Grid Block Minima
Given a 2D integer grid of size M x N and a block size K x K, find the minimum value within every possible K x K subgrid. The output should be a grid of size (M-K+1) x (N-K+1) where result[i][j] is the minimum of the subgrid starting at (i, j).
Constraints: 1 <= K <= M, N <= 1000. Aim for a solution more efficient than O(M * N * K^2).
Part 2: Recipe Dependency Resolution
You are given a list of recipes, where each recipe has a name and a list of required ingredients. Some ingredients are 'base' items, while others are 'derived' recipes that must be prepared first. Return an order in which the recipes should be prepared to satisfy all dependencies, or return an empty list if a circular dependency exists.
Interface:
def get_preparation_order(recipes):
# recipes is a dictionary: { 'recipe_name': ['ingredient1', 'recipe2', ...] }
# returns a list of strings representing the preparation order
Example: Input:
{
"Cake": ["Flour", "Frosting"],
"Frosting": ["Sugar", "Butter"],
"Flour": []
}
Output: ["Flour", "Frosting", "Cake"] (or similar valid topological sort)
Edge Cases:
- Empty input.
- Disconnected components (multiple independent recipe trees).
- Cycles (e.g., A needs B, B needs A).
Hints
Hint 1
For the grid problem, consider using a sliding window approach with a deque (monotonic queue) to reduce the complexity to O(M * N).
Hint 2
For the recipe problem, treat the recipes and ingredients as nodes in a directed graph and perform a topological sort using Kahn's algorithm or DFS.
Hint 3
When handling the grid, solve the 1D sliding window minimum problem first, then apply it horizontally and then vertically.
Follow-up questions
- How would you modify the recipe dependency solver if you had a limited 'preparation station' capacity, allowing you to prepare multiple non-dependent recipes simultaneously?
- If the grid values change frequently, how could you optimize the minimum-value query for specific blocks without recomputing the entire grid?
- What are the space complexity trade-offs if you use a Segment Tree versus a Monotonic Queue for the grid problem?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.