DIY: Read N Characters Given Read4 II — Call Multiple Times

Solve the interview question "Read N Characters Given Read4 II — Call Multiple Times" in this lesson.

Problem statement

Suppose that you can only read a given File using a specific API method called read4. You will implement the read method to read n characters from the File. This read method can be called multiple times.

read4() API:

The read4() API reads the next four consecutive characters from the File, until the File no longer has any characters that need to be read. After reading, the read4() method writes the characters into the array named buff.

The read4() method uses its own file pointer to keep track of the characters that have already been read.

Function Definition:

  • Parameter: obj

  • Return: {buff, obj_reader}

Here, the variable obj refers to the struct object of the AdServing module which comprises of the Buffer state and the Reader module struct object. The latter consists of an integer as its component which keeps track of the characters already been read.

Note: that the variable buff is a destination, not a source.

Let’s look at an example of how the read4 method works.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.