Problem description:

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Example 1:

1
2
3
Input: buf = "abc", n = 4
Output: "abc"
Explanation: The actual number of characters read is 3, which is "abc".

Example 2:

1
2
Input: buf = "abcde", n = 5 
Output: "abcde"

Note:
The read function will only be called once for each test case.

Solution:

Question to ask:

  1. read4 can be use multiple times?
  2. output type

One thing to notice is that the read will only be called once. The read4 will return how many characters it read from the input char *buf. So we can use a variable to cumulate the sum of characters that read by read4. Once the return value of read4 is smaller than 4, that means we reached the last position.

Make sure to move the position in char *buf for read4 to read next position.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
int read(char *buf, int n) {
int complete= 0;
while(n){
int tmp = min(read4(buf), n);
complete+= tmp;
buf+= tmp; //move the char pointer to next position
if(tmp< 4)
break;
n-= 4;
}
return complete;
}
};

time complexity: $O(n)$
space complexity: $O(1)$
reference: