Skip to the code
cf.
+10 XP

#283 Fixed-Size Log Buffer

easy

An embedded analytics script must not grow its memory, so it stores pending log entries in a circular queue of fixed size capacity. Write a class LogBuffer:

  • new LogBuffer(capacity) creates an empty buffer.
  • enqueue(entry) adds an entry at the back and returns true, or returns false if the buffer is full.
  • dequeue() removes the oldest entry and returns true, or returns false if the buffer is empty.
  • front() and rear() return the oldest and newest entries, or -1 if empty.
  • isEmpty() and isFull() return booleans.

Use a fixed array of size capacity with wrap-around indexes; don't grow or shift an array.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new LogBuffer(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["LogBuffer","enqueue","enqueue","enqueue","enqueue","rear","isFull","dequeue","enqueue","rear","front"]
[[3],[1],[2],[3],[4],[],[],[],[4],[],[]]
Output: [null,true,true,true,false,3,true,true,true,4,2]

The 4th entry is refused while full. After one dequeue, 4 fits by wrapping into slot 0.

Example 2

Input: ["LogBuffer","front","rear","dequeue","isEmpty"]
[[2],[],[],[],[]]
Output: [null,-1,-1,false,true]

Everything on an empty buffer gives -1 or false, and it is empty.

Constraints

  • 1 <= capacity <= 1000
  • 0 <= entry <= 1000
  • At most 3000 calls.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).