/157. Read N Characters Using Read4 API

157. Read N Characters Using Read4 API

Easy
Arrays42.5% acceptance

Given a function read4(buf4) that reads up to 4 characters from a file and writes them into buf4, implement a function read(buf, n) that reads up to n characters from the file and writes them into buf. The function should return the number of characters actually read. The file may contain fewer than n characters. The read4 API will be provided and should be used to read from the file.

Example 1

Input: buf = []; n = 7

Output: 7

Explanation: If the file contains at least 7 characters, buf will be filled with the first 7 characters.

Example 2

Input: buf = []; n = 3

Output: 3

Explanation: If the file contains at least 3 characters, buf will be filled with the first 3 characters.

Example 3

Input: buf = []; n = 10

Output: 5

Explanation: If the file contains only 5 characters, buf will be filled with those 5 characters.

Constraints

  • 1 <= n <= 10^5
  • The file contains at most 10^5 characters.
  • buf is a writable list of characters with at least n capacity.
  • read4(buf4) returns the number of characters read (0 to 4), and writes them into buf4.
Python (current runtime)

Case 1

Input: buf = []; n = 6

Expected: 6

Case 2

Input: buf = []; n = 2

Expected: 2

Case 3

Input: buf = []; n = 12

Expected: 8