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
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

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
topological sort
min-heap
greedy
determinism
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • Input: names (distinct strings) and edges [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...


Submit Your Answer
Markdown supported