In a data warehouse, tables form a directed acyclic graph (DAG) of dependencies.
An edge A -> B means "B depends on data from A" (B cannot be refreshed until A is refreshed).
When a source table is updated (e.g., backfilled), you must identify ALL downstream tables
that are affected and need recomputation to maintain data integrity.
Given:
- A DAG represented as adjacency list: table_name -> [dependent_tables]
- A set of updated tables (the starting points)
Implement:
def minimal_recompute_set(
dag: Dict[str, List[str]],
updated_tables: List[str]
) -> List[str]:
"""
Returns the minimal set of all tables that must be recomputed after the given
tables are updated. This includes the updated tables themselves.
Text
Args:
dag: adjacency list; edge A->B means B depends on A
updated_tables: list of table names that were just updated
Returns:
Sorted list of all affected tables (including updated_tables)
"""
def topological_sort_with_priorities(
dag: Dict[str, List[str]],
node_priority: Dict[str, int],
nodes: List[str]
) -> List[str]:
"""
Return a topological sort of the given nodes using Kahn's algorithm.
Break ties by node_priority (higher priority = earlier in sort).
Text
Returns:
List of nodes in valid topological order, with higher-priority nodes
appearing earlier (among nodes at the same topological level)
"""
Constraints:
- DAG has up to 10,000 nodes and 50,000 edges
- Use BFS or DFS for reachability; Kahn's algorithm for topological sort
- O(V + E) time complexity required
- No cycles guaranteed (it's a DAG)
Input Format:
Line 1: n_tables
Line 2: n_edges
Lines 3 to 2+n_edges: source_table dependent_table (one edge per line)
Line 3+n_edges: n_updated
Lines 4+n_edges to 3+n_edges+n_updated: table_name
Output Format:
One table name per line, in sorted order