Skip to content
BytePatterns

Lock Order That Prevents Deadlock

MediumConcurrency#lock-ordering#topological-sort#min-heap~25m

Problem

A service has several code paths, and each one takes a list of locks in the order given, holding every earlier lock while it takes the next. Deadlock is impossible if there is one global lock order that every path already follows. Given the paths, return such an order as a list of lock names, choosing the alphabetically smallest free lock at each position so the answer is unique. If the paths contradict each other, for example one takes a before b and another takes b before a, no order exists: return None. There are up to 10,000 locks.

Examples

Input:  [["accounts", "ledger"], ["ledger", "audit"], ["accounts", "audit"]]
Output: ['accounts', 'ledger', 'audit']
Why:    ledger must come before audit, so audit waits even though it is alphabetically first
Input:  [["a", "b"], ["b", "c"], ["c", "a"]]
Output: None
Why:    the three paths form a cycle, which is exactly the shape a deadlock needs
Input:  [["cache"], ["db", "cache"], ["log"]]
Output: ['db', 'cache', 'log']
Why:    edge case, a path with one lock adds a lock but no ordering rule

Hints

0 / 3

Stuck on the idea rather than the code? Deadlock covers it.