Blocking Connection Pool Operation Trace
Problem statement
Simulate the observable behavior of a blocking database connection pool over a finite operation trace.
The pool is initialized with maxSize independent connections numbered 0 through maxSize - 1. All connections begin idle in increasing-ID FIFO order. Each row operations[i] = [type, value] is processed in input order:
type = 0isGETfor the unique request IDvalue. If an idle connection exists, remove the FIFO head, mark it active, and emit[i, 0, value, connectionId]. Otherwise the call blocks in a FIFO waiter queue and emits nothing until a later valid release transfers a connection to it.type = 1isRELEASEfor connection IDvalue. Emit[i, 1, value, success], wheresuccessis1only when that connection is currently active. A failed or repeated release changes nothing. After a successful release, transfer the connection directly to the oldest blockedGET, if one exists, and then emit that request's assignment event. Otherwise append the connection to the idle FIFO queue.type = 2isACTIVE_COUNT; ignorevalueand emit[i, 2, activeCount, 0].
Events are returned in emission order. A GET still blocked after the final operation never completes and produces no event. Return the complete event list as an int[][].
Interview extensions
- Describe a real thread-safe implementation using a semaphore, a blocking queue, and ownership tracking.
- Explain how to prevent or recover leaked connections with bounded leases, health checks, and observability.
Function
simulateConnectionPool(maxSize: int, operations: int[][]) → int[][]Examples
Example 1
maxSize = 2operations = [[0,101],[0,102],[2,0],[0,103],[1,0],[2,0],[1,0],[1,1],[2,0]]return = [[0,0,101,0],[1,0,102,1],[2,2,2,0],[4,1,0,1],[3,0,103,0],[5,2,2,0],[6,1,0,1],[7,1,1,1],[8,2,0,0]]Requests 101 and 102 receive both connections. Request 103 blocks. Releasing connection 0 emits the release result and then completes request 103 with that same connection.
Example 2
maxSize = 1operations = [[0,7],[1,0],[1,0],[2,0]]return = [[0,0,7,0],[1,1,0,1],[2,1,0,0],[3,2,0,0]]The first release succeeds. The repeated release is rejected and does not change the active count.
Example 3
maxSize = 1operations = [[0,10],[0,20],[0,30],[1,0],[1,0],[2,0]]return = [[0,0,10,0],[3,1,0,1],[1,0,20,0],[4,1,0,1],[2,0,30,0],[5,2,1,0]]Requests 20 and 30 wait in FIFO order. Each successful release transfers connection 0 directly to the oldest waiter.
Example 4
maxSize = 1operations = [[0,1],[0,2],[2,0]]return = [[0,0,1,0],[2,2,1,0]]Request 2 remains blocked when the trace ends, so it has no completion event.
Constraints
1 <= maxSize <= 1000001 <= operations.length <= 200000- Each
operations[i]contains exactly two integers. 0 <= type <= 2- Every
GETrequest ID is positive and unique. - A
RELEASEvalue may be any signed 32-bit integer; it succeeds only for a currently active connection ID. - The number of emitted events fits in memory.