Datadog questions

Buffered File Writer

DatadogPhone screenMedium

A file accepts writes, and every write to it is slow. You implement a writer that sits in front of the file and collects characters in an in-memory buffer, so the file receives fewer, larger writes. The buffer holds at most capacity characters, and every character counts as one byte. When the buffer holds exactly capacity characters, its contents go to the file as a single write and the buffer is emptied. Characters reach the file in the order they were written; none are lost or sent twice. Each test creates one writer and checks the return value of every operation.

Part 1: Buffered writes and flush

Implement a writer that batches characters before they reach a slow file.

__init__(capacity) sets the buffer limit capacity.

write(data) appends the characters of data to the buffer. Each time the buffer reaches capacity characters, its contents are sent to the file as one string and the buffer is emptied; the rest of data then keeps filling the buffer, so one call may send several strings. Return the list of strings sent during this call, in order.

flush() sends whatever the buffer currently holds as one string and empties it, returning that string in a list. Flushing an empty buffer sends nothing and returns an empty list.

Both methods return an empty list when nothing was sent.

  1. Example 1
    init
    [8]
    operations
    [["write",["abc"]],["write",["defgh"]],["write",["ij"]],["flush",[]],["flush",[]]]
    Output
    [[],["abcdefgh"],[],["ij"],[]]

    Why: abc leaves 5 free slots, so the next write fills the buffer exactly and abcdefgh goes out as one write. ij waits in the buffer until flush sends it; the second flush finds the buffer empty and sends nothing.

Constraints

  • 1 <= capacity <= 10^4
  • 1 <= len(data) <= 10^5
  • data contains only printable ASCII characters
  • 1 <= len(operations) <= 10^4
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question