Practice problem · medium
A logging agent on a server hands log lines to a shipper through a buffer with a fixed number of slots. The agent writes lines at the back. The shipper reads them from the front, in the order they were written.
When the buffer is full, a write is refused, so the agent knows to wait. When a line is read, its slot is free again. Memory use must stay fixed, so the buffer cannot grow.
Write run_log_buffer(capacity, commands, values).
capacity is the number of slots. The buffer starts empty.commands is a list of words: write, read, front, rear, empty or full.values[i] belongs to commands[i]. It is the line number to write for a write, and it is ignored for the other commands.write adds a line at the back, if there is a free slot.read removes the line at the front.front and rear read the line at the front and at the back, without removing it.empty asks whether the buffer holds no lines. full asks whether every slot is used.write and read, the answer is 1 when it worked and 0 when it did not. A write to a full buffer fails, and so does a read from an empty one.front and rear, the answer is the line number, or -1 when the buffer is empty.empty and full, the answer is 1 for yes and 0 for no.Input: capacity = 2, commands = ["write", "write", "write", "full", "read", "write", "rear"], values = [10, 20, 30, 0, 0, 40, 0]
Output: [1, 1, 0, 1, 1, 1, 40]| Step | Command | Lines in the buffer (front to back) | Answer |
|---|---|---|---|
| 1 | write 10 |
10 |
1 |
| 2 | write 20 |
10 20 |
1 |
| 3 | write 30 |
10 20 (no free slot) |
0 |
| 4 | full |
10 20 |
1 |
| 5 | read |
20 |
1 |
| 6 | write 40 |
20 40 (slot 0 is reused) |
1 |
| 7 | rear |
20 40 |
40 |
The third write is refused because both slots are used. After a read frees a slot, the write of 40 works, and 40 is at the back.
Input: capacity = 1, commands = ["read", "empty", "front"], values = [0, 0, 0]
Output: [0, 1, -1]Reading from an empty buffer fails.
Input: capacity = 3, commands = ["write", "front", "rear", "full"], values = [5, 0, 0, 0]
Output: [1, 5, 5, 0]With one line, the front and the rear are the same line.
1 ≤ capacity ≤ 10^51 ≤ length of commands ≤ 10^5commands has the same length as valueswrite, read, front, rear, empty or full0 ≤ values[i] ≤ 10^6A buffer that shifts every line forward after a read costs up to capacity steps for each read. With a capacity of 50,000 and 100,000 commands, that is billions of steps, which is too slow.
So no line may move. Keep a head index and a count, and let the indexes wrap round the fixed block.
run_log_buffer · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.