Smallest Lexicographic Order to Apply Schema Migrations
Last updated: November 29, 2026
Quick Overview
Database migrations are named by strings and some must run before others. Given migration names and pairs [a, b] meaning a must run before b, return the lexicographically smallest valid order, or an empty list if no valid order exists.
Meta
November 29, 20260
0
0 solved
Database migrations are named by strings and some must run before others. Given migration names and pairs [a, b] meaning a must run before b, return the lexicographically smallest valid order, or an empty list if no valid order exists.
A Meta technical screen variant of topological sort, framed around applying schema migrations to sharded MySQL in a reproducible order. The interviewer wants a deterministic order so every shard runs the same sequence, and checks that you swap Kahn's queue for a min-heap and explain why that gives the lexicographically smallest result.
What the Interviewer Expects
- Replace the FIFO queue in Kahn's algorithm with a min-heap
- Argue the greedy choice is optimal for lexicographic order
- Detect cycles by comparing output length with node count
- State O((V + E) log V) time
- Explain why determinism matters across shards
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Why does DFS-based topological sort not give the smallest order directly?
- How would you find the order that places a specific migration as early as possible?
- What changes if migrations arrive over time and you must emit them as soon as they are safe?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
names(distinct strings) andedges[a, b]. - Output: the lexicographically smallest sequence (compared element by element) that respects every edge, or
[]if a cycle exists....
High-Level Design
Kahn's algorithm lets us pick any node among those currently available (in-degree zero). To minimize the sequence lexicographically, always pick the smallest available name. This greedy choice is safe...