Code RoomLock trace impossibility
EasyPrep Room Coding #4712

Lock trace impossibility

CodingConcurrencyEntry–Mid~15 min

A render farm audits the lock trace its job runner recorded. Each event is a string "worker|action|lock", for example "w2|lock|mesh_cache", and the action is either "lock" or "unlock". The locks are reentrant: a worker that already holds a lock may lock it again, which raises its hold count by one, and every unlock lowers that count by one. A lock becomes free only when its count falls back to zero. An event is impossible when a worker locks a lock that a different worker currently holds, or unlocks a lock that is free or held by someone else. Read the events in order and return the 1-based position of the first impossible event, or 0 when the whole trace is consistent. Locks still held at the end are fine.

Implement
first_trace_defect(events: list[str]) → int
Examples
in[["w1|lock|mesh","w1|lock|mesh","w1|unlock|mesh","w2|lock|mesh"]]out4
in[["w1|lock|mesh","w1|unlock|mesh","w2|lock|mesh","w2|unlock|mesh"]]out0
in[["w3|lock|shader","w4|unlock|shader"]]out2
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 15 min
InputExpectedGot
[["w1|lock|mesh","w1|lock|mesh","w1|unlock|mesh","w2|lock|mesh"]]4not run yetsample
[["w1|lock|mesh","w1|unlock|mesh","w2|lock|mesh","w2|unlock|mesh"]]0not run yetsample
[["w3|lock|shader","w4|unlock|shader"]]2not run yetsample