FastPrepSegmented Durable Key-Value Store
Problem · Design

Segmented Durable Key-Value Store

Learn this problem
MediumOpenAI logoOpenAIFULLTIMEPHONE SCREEN

Problem statement

Simulate a durable string key-value store over an ordered batch of commands. The durable store is an append-only log split greedily across numbered segments, each with capacity 1024 bytes.

Commands

  • PUT key value: append a record and set key to value using last-write-wins semantics. Return OK. The value is the entire suffix after the second space and may be empty.
  • GET key: return VALUE:value for a present key, or NOT_FOUND.
  • RELOAD: discard the in-memory map and reconstruct it by replaying every complete record in segment order. Return OK.
  • SEGMENTS: return SEGMENTS:s1,s2,..., where each value is the used-byte count of one durable segment in order. With no records, return SEGMENTS:.

Record encoding and segmentation

All keys and values are printable ASCII, so one character occupies one byte. Encode a record as keyLength:keyvalueLength:value, where each length is written in base 10. A record is never split. Before an append that would make the current segment exceed 1024 bytes, start a new segment. Every encoded record is guaranteed to fit in one segment.

Return one result string for every command, in command order.

Function

runSegmentedStore(commands: String[]) → String[]

Examples

Example 1

commands = ["PUT color blue","GET color","PUT color green","RELOAD","GET color","SEGMENTS"]return = ["OK","VALUE:blue","OK","OK","VALUE:green","SEGMENTS:27"]

The two encoded records use 13 and 14 bytes. Reload replays both records, so the later value green wins.

Example 2

commands = ["GET missing","SEGMENTS","PUT a " ,"RELOAD","GET a","SEGMENTS"]return = ["NOT_FOUND","SEGMENTS:","OK","OK","VALUE:","SEGMENTS:4"]

An empty value is durable. Its record is 1:a0:, which uses 4 bytes.

Constraints

  • 1 <= commands.length <= 2000
  • Commands are well formed and use one of the four documented operation names.
  • Keys are non-empty printable-ASCII strings of length at most 100 and contain no spaces.
  • Values contain printable ASCII characters, may contain spaces, and have length at most 900.
  • The total length of all command strings is at most 2 * 10^5.
  • Every encoded record uses at most 1024 bytes.

More OpenAI problems

drafts saved locally
public String[] runSegmentedStore(String[] commands) {
    // Write your code here
}
commands["PUT color blue","GET color","PUT color green","RELOAD","GET color","SEGMENTS"]
expected["OK", "VALUE:blue", "OK", "OK", "VALUE:green", "SEGMENTS:27"]
checking account