[LeetCode] 158. Read N Characters Given Read4 II - Call multiple times

Problem

Given a file and assume that you can only read the file using a given method read4, implement a method read to read n characters. Your method read may be called multiple times.

Method read4:

The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf.

The return value is the number of actual characters read.

Note that read4() has its own file pointer, much like FILE *fp in C.

Definition of read4:

1
2
3
4
    Parameter:  char[] buf
    Returns:    int

Note: buf[] is destination not source, the results from read4 will be copied to buf[]

Below is a high level example of how read4 works:

1
2
3
4
5
File file("abcdefghijk"); // File is "abcdefghijk", initially file pointer (fp) points to 'a'
char[] buf = new char[4]; // Create buffer with enough space to store characters
read4(buf); // read4 returns 4. Now buf = "abcd", fp points to 'e'
read4(buf); // read4 returns 4. Now buf = "efgh", fp points to 'i'
read4(buf); // read4 returns 3. Now buf = "ijk", fp points to end of file

Method read:

By using the read4 method, implement the method read that reads n characters from the file and store it in the buffer array buf. Consider that you cannot manipulate the file directly.

The return value is the number of actual characters read.

Definition of read:

1
2
3
4
   Parameters:  char[] buf, int n
    Returns:    int

Note: buf[] is destination not source, you will need to write the results to buf[]

Example 1:

1
2
3
4
5
6
File file("abc");
Solution sol;
// Assume buf is allocated and guaranteed to have enough space for storing all characters from the file.
sol.read(buf, 1); // After calling your read method, buf should contain "a". We read a total of 1 character from the file, so return 1.
sol.read(buf, 2); // Now buf should contain "bc". We read a total of 2 characters from the file, so return 2.
sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.

Example 2:

1
2
3
4
File file("abc");
Solution sol;
sol.read(buf, 4); // After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3.
sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.

Note:

  1. Consider that you cannot manipulate the file directly, the file is only accesible for read4 but not for read.
  2. The read function may be called multiple times.
  3. Please remember to RESET your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see here for more details.
  4. You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters.
  5. It is guaranteed that in a given test case the same buffer buf is called by read.

Explanation

  1. The difference between this question and the first version is that the read() function will be called multiple times.

  2. The trouble here will be as the following example if using the first version solution:

1
2
3
  file: “abcdefg”
  read(3) read(2) read(2) should be “abc” “de” “fg”
  but using first version solution it will print “abc” “ef” “”
  1. This is because when you use read4() to read, the pointer to read file has already moved to e after the first call of read4(). So it’s not correct any more.

  2. In order to solve, we need to persist the characters that has been already read by using read4 but it’s not put into the result of read().

  3. In the solution below, we are using a buf4[] to store the characters read by using read4 and also a buf4Size and buf4Index to keep track of the size of the buf4 and the index to use in buf4[].

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * The read4 API is defined in the parent class Reader4.
 *     int read4(char[] buf);
 */
public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Number of characters to read
     * @return    The number of actual characters read
     */
    char[] buf4 = new char[4];
    int buf4Index = 0;
    int buf4Size = 0;

    public int read(char[] buf, int n) {
        int i = 0;
        while (i < n) {
            if (buf4Index >= buf4Size) {
                buf4Index = 0;
                buf4Size = read4(buf4);
                if (buf4Size == 0) {
                    break;
                }
            }
            buf[i] = buf4[buf4Index];
            buf4Index += 1;
            i += 1;
        }

        return i;
    }
}

Source:

158 LeetCode Java: Read N Characters Given Read4 II – Call multiple times Add to List QuestionEditorial Solution – Hard