FastPrepRead N Characters with read4 Across Multiple Calls

Read N Characters with read4 Across Multiple Calls

Bloomberg LP logoBloomberg LP● HardNEW GRADONSITE INTERVIEW
Learn

Problem statement

A stateful reader consumes characters from file from left to right. Its only low-level operation is read4, which consumes up to four remaining characters. Characters fetched by read4 but not returned by the current call must remain buffered for later calls.

The array reads describes consecutive calls to read(n) on the same reader. For each value n, return a string containing up to n next unread characters, or fewer when the file reaches end-of-file.

Return one string for every requested call, preserving the reader state across all calls.

Function

readAcrossCalls(file: String, reads: int[]) → String[]

Examples

Example 1

file = "abcdef"reads = [1,3,4]return = ["a","bcd","ef"]

The first call returns one character while retaining the other fetched characters. The next call continues at b, and the last call receives the two remaining characters.

Example 2

file = "abc"reads = [4,1]return = ["abc",""]

The first call reaches end-of-file after three characters. Every later call returns an empty string.

Example 3

file = "abcdefghijkl"reads = [5,2,5]return = ["abcde","fg","hijkl"]

All three calls share one reader, so the chunks concatenate to the original file without duplication or omission.

Constraints

  • 0 <= file.length <= 100000.
  • 1 <= reads.length <= 100000.
  • 0 <= reads[i] <= 100000.
  • The sum of all values in reads is at most 100000.
  • file contains printable ASCII characters other than line breaks.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public String[] readAcrossCalls(String file, int[] reads) {
    // Write your code here.
}
file"abcdef"
reads[1,3,4]
expected["a", "bcd", "ef"]
Checking account…