Buffered Reading with a Read4-Style Stream
Problem statement
Implement a buffered reader over a Read4-style stream. For this practice adapter, data is the mock stream and requests lists consecutive read sizes. One upstream pull returns the next at most four characters and advances the shared stream cursor; it returns an empty chunk at end of stream.
For each requested size n, return the next n unread characters, or all remaining characters if fewer than n remain. Preserve any unused characters from a pulled chunk for the next request. A zero-size request returns an empty string and consumes no characters. End of stream is permanent; later requests return empty strings.
Return one string per request, in request order. Preserve every character, including spaces, punctuation and case. Each function call starts a new reader; all requests inside that call share its state. You may buffer the whole stream for a simple solution, but aim to keep only one four-character upstream chunk between requests. All characters are printable ASCII, so one character is one byte.
Function
readBuffered(data: String, requests: int[]) → String[]Examples
Example 1
data = "abcdefgh"requests = [1,2,4,3]return = ["a","bc","defg","h"]The requests receive a, bc, defg and h. After the first upstream chunk abcd is pulled, its unused characters remain available for later requests.
Example 2
data = "ab cd!"requests = [0,4,0,4,1]return = ["","ab c","","d!",""]The zero requests consume nothing. The first positive request returns ab c; the next returns the remaining d!. The last request is after end of stream.
Example 3
data = ""requests = [3,0,2]return = ["","",""]The stream is empty, so every requested result is an empty string.
Constraints
0 <= data.length <= 100001 <= requests.length <= 10000 <= requests[i] <= 10000- Every character in
datais printable ASCII, with code from 32 through 126.