439. Read N Characters Given Read4

You are given a file and a function read4 that reads up to 4 consecutive characters from the file into a buffer. Your task is to implement a function read that reads up to n characters using read4.

read4 Function

Definition:

def read4(buf4: List[str]) -> int:

  • Functionality: Reads up to 4 characters from the file into buf4 and returns the number of characters actually read.
  • File Pointer: read4 maintains its own internal file pointer, similar to FILE *fp in C.

Example Behavior of read4

file = "abcde"

buf4 = [""] * 4

read4(buf4) # Returns 4, buf4 = ["a", "b", "c", "d"], file pointer moves to "e"

read4(buf4) # Returns 1, buf4 = ["e"], file pointer reaches EOF

read4(buf4) # Returns 0, buf4 = [], file pointer remains at EOF

Implementing read Function

Your task is to implement the read function:

def read(buf: List[str], n: int) -> int:

Parameters:

  • buf: A destination buffer to store the read characters.
  • n: The number of characters to read.

Returns:

  • The actual number of characters read from the file.

Constraints:

  • You cannot access the file directly; you can only use read4.
  • The read function is called only once per test case.
  • buf has enough space for n characters.

Example 1:

Input: file = "abc", n = 4

Output: 3

Explanation: The file has only "abc". Since n=4, we try to read 4 characters but can only get 3.

Example 2:

Input: file = "abcde", n = 5

Output: 5

Explanation: The file contains 5 characters, and we request 5, so all characters are read.

Now Your Turn!

Pick the correct output for the given input

Input: file = "abcdABCD1234", n = 12

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ file.length ≤ 500
  • 1 ≤ n ≤ 1000
  • file consists only of English letters and digits.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
// Your code goes here
}
};
Test Case

Input:

File
N