Buffered File Writer with Partial Writes
Problem statement
Implement a buffered file writer. It has a fixed byte buffer of capacity bytes and an initially empty mock file. Every data byte must enter the buffer before it can reach the file. Process actions in order.
W: <data>appends the payload bytes. Fill the buffer from left to right. Whenever it becomes full, flush it completely, then continue with any remaining payload. A payload may be empty.Fflushes all pending bytes. Flushing an empty buffer does not call the file.
A flush may need several file calls. Each call offers all currently pending bytes, in order. The next unused value in limits is the maximum number of bytes that call accepts. It accepts the smaller of that limit and the number offered, always from the front. Consume one limit for every call, including a zero-byte call. After the limit array is exhausted, each call accepts all bytes offered.
Keep retrying a flush until the buffer is empty. A zero-byte call leaves its contents unchanged. This finite mock always makes progress after its scripted limits are exhausted. Do not flush automatically at the end of the action list.
After every action, return a two-string snapshot [fileContents, pendingBuffer]. Preserve spaces, case and byte order. Return snapshots in action order. The fixed buffer must never hold more than capacity bytes; the mock file and returned snapshots are outside that buffer budget. All payloads use printable ASCII, so one character is one byte.
Function
simulateBufferedWrites(capacity: int, actions: String[], limits: int[]) → String[][]Examples
Example 1
capacity = 4actions = ["W: ab","W: cdef","F"]limits = []return = [["","ab"],["abcd","ef"],["abcdef",""]]After the first write, ab is pending. The next write fills and flushes abcd, then leaves ef pending. The explicit flush appends ef to the file.
Example 2
capacity = 3actions = ["W: abcde","F","F","W: !"]limits = [1,0,1,2]return = [["abc","de"],["abcde",""],["abcde",""],["abcde","!"]]The first full buffer is abc. Its file calls accept a, nothing, b, then c. The buffer then holds de. The first explicit flush writes those bytes; the next flush does nothing. The final write leaves ! pending.
Example 3
capacity = 1actions = ["F","W: xy","W: ","F"]limits = [0,1,0]return = [["",""],["xy",""],["xy",""],["xy",""]]The initial empty flush consumes no limit. Each byte fills the one-byte buffer. The calls for x accept zero then one byte; the calls for y accept zero then one byte after the script ends. The empty write and final empty flush leave the file unchanged.
Constraints
1 <= capacity <= 10001 <= actions.length <= 5001 <= actions[i].length <= 25030 <= limits.length <= 200000 <= limits[i] <= 20000- Each action is exactly
F, or starts with exactlyW:followed by zero or more printable ASCII characters. - The total number of payload bytes across all write actions is at most 2500.
- The sum of all string lengths in the returned snapshots is at most 5000.