Code RoomTwo-phase locking simulator
HardPrep Room Coding #310

Two-phase locking simulator

CodingConcurrencySenior–Staff~35 min

Simulate strict two-phase locking (S2PL) with a deterministic grant policy to detect blocking. ops is a list of [txn, action, key] in order. action is 'lock' (acquire an exclusive lock on key) or 'commit' (release ALL locks the txn holds). A 'lock' request is GRANTED immediately if the key is unlocked; otherwise the requesting txn BLOCKS and the op is recorded as a block. Once a txn is blocked on a key, it cannot issue further ops until unblocked — but to keep this deterministic, assume blocked requests are simply recorded and SKIPPED (the txn's later ops still process). When a 'commit' releases a key that has blocked waiters, the LONGEST-waiting blocked txn for that key (earliest block, by op index) is retried and, if now grantable, granted (recorded as a grant at the commit's position). Return a list of [op_index, txn, 'grant' | 'block'] for every lock request and every retry-grant, in chronological order of when they resolve.

Implement
s2pl_trace(ops: list[list]) → list[list]
Examples
in[[[1,"lock","x"],[2,"lock","x"],[1,"commit",""]]]out[[0,1,"grant"],[1,2,"block"],[2,2,"grant"]]
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 35 min
InputExpectedGot
[[[1,"lock","x"],[2,"lock","x"],[1,"commit",""]]][[0,1,"grant"],[1,2,"block"],[2,2,"grant"]]not run yetsample