Skip to content
BytePatterns

Deadlock in a Wait-For Graph

EasyGraphs#cycle-detection#graph-colouring#topological-sort~20m

Problem

A database tracks n transactions numbered 0 to n - 1. Each pair [a, b] in waits means transaction a is waiting for a lock that transaction b holds. A deadlock exists when some group of transactions waits on each other in a circle. Return True if the wait-for graph contains a deadlock, otherwise False.

Examples

Input:  n = 4, waits = [[0, 1], [1, 2], [2, 0], [3, 0]]
Output: True
Why:    0 waits for 1, 1 for 2 and 2 for 0, so none of them can ever proceed
Input:  n = 4, waits = [[0, 1], [0, 2], [1, 3], [2, 3]]
Output: False
Why:    two chains meet at 3, but meeting is not a circle, and 3 waits for nobody
Input:  n = 2, waits = []
Output: False
Why:    edge case, nobody waits, so nobody is stuck

Hints

0 / 3

Stuck on the idea rather than the code? Cycles in a Directed Graph covers it.