Databricks questions

Buffered Writer

DatabricksOnsiteMedium

You are implementing BufferedWriter, a log writer that collects lines in memory and moves them to a file in batches. Each line has the form thread:message. The file only ever receives lines from the buffer, in the order they were written. Each test creates one BufferedWriter(capacity) and calls its methods in sequence; every return value is checked.

Part 1: Buffer and flush

Implement three methods.

  • write(thread, message) adds the line thread:message to the buffer. If the buffer then holds capacity lines, it is flushed immediately: all buffered lines move to the file. Return the number of lines in the buffer afterwards.
  • flush() moves every buffered line to the file and returns how many lines it moved. Flushing an empty buffer returns 0.
  • close() flushes the remaining buffered lines and returns the full contents of the file as a list of lines, in the order they were written. It is the last call of every test.
  1. Example 1
    init
    [2]
    operations
    [["write",["t1","alpha"]],["write",["t2","beta"]],["write",["t1","gamma"]],["flush",[]],["write",["t3","delta"]],["close",[]]]
    Output
    [1,0,1,1,1,["t1:alpha","t2:beta","t1:gamma","t3:delta"]]

    Why: With capacity 2 the second write fills the buffer and flushes it automatically, so it returns 0. gamma is buffered, flush writes it and returns 1, delta is buffered, and close flushes it and returns the whole file in write order.

Constraints

  • 1 <= capacity <= 10^5
  • 1 <= len(thread) <= 20
  • 1 <= len(message) <= 20
  • thread and message contain no : or newline
  • 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