Stockroom Quorum Read

EasysimulationAlso known as Quorum Read

A hardware shop keeps each item's stock count on 3 replicas. Every write carries a version number one higher than the last, and counts as done once 2 replicas store it (W = 2). A read asks all 3 and waits for the first 2 answers (R = 2). Since 2 + 2 > 3, those answers always include a replica holding the latest completed write. A slow or down replica never answers.

This is the quorum read of leaderless key-value stores (see Replication and Design a Key-Value Store). It only works if the read picks the newest answer, not the first.

Your task

Write quorumRead(replies, r). replies lists what each replica sent, in arrival order. Each entry is [version, value], or null for a replica that timed out.

The coordinator takes the first r entries that are not null and ignores everything after them, even a newer version, because it has already answered. Return [version, value] for the highest version among those r replies. If fewer than r replicas answered, the read fails: return an empty list.

Two replies with the same version always carry the same value.

quorumRead(replies: int[][], r: int) → int[]

Examples

Example 1
Input
replies = [[4, 12], null, [5, 9]]
r = 2
Output
[5, 9]
Why

The first reply is version 4 (12 in stock). The second replica timed out, so the coordinator keeps waiting. The third reply is version 5 (9 in stock). That makes 2 replies, and version 5 is newer, so the answer is 9. Returning the first reply, 12, would show stock that was already sold.

Example 2
Input
replies = [[7, 30], [6, 31], [8, 29]]
r = 2
Output
[7, 30]
Why

The first two replies, versions 7 and 6, already make a quorum of 2, so the coordinator answers with version 7. Version 8 arrives too late to be seen. That is allowed: R + W > N only promises that the read sees the latest write that had finished, and a write still on its way to its second replica has not finished.

Example 3
Input
replies = [null, [3, 5], null]
r = 2
Output
[]
Why

Only one replica answered, and the read needs 2. Returning version 3 anyway would drop the overlap guarantee, so the read fails and the caller can retry.

Constraints

  • 1 ≤ replies.length ≤ 7
  • 1 ≤ r ≤ replies.length
  • 1 ≤ version ≤ 1,000,000,000
  • −1,000,000 ≤ value ≤ 1,000,000
Start with brute force

Returning the highest version in the whole list is wrong, not slow: the coordinator answers once it has r replies, so later ones never reach it (the second example).

Returning the first non-null reply is a read with R = 1, and with W = 2 on 3 replicas it can miss the latest write (the first example).

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code