/158. Read N Characters Given read4 II - Call Multiple Times

158. Read N Characters Given read4 II - Call Multiple Times

Hard
Arrays43.2% acceptance

Implement a class that reads characters from a file using a provided API read4(char[] buf), which reads up to 4 characters at a time and returns the actual number of characters read. The class should provide a method read(char[] buf, int n) that reads n characters into buf, and can be called multiple times. The read method should return the actual number of characters read. The file is only accessible through the read4 API. The state should be maintained across multiple calls to read.

Example 1

Input: calls = [(5,), (3,), (6,)] file_content = "abcdefghijklm" # Expected outputs for each call

Output: [5, 3, 5]

Explanation: First call reads abcde, second reads fgh, third reads ijklm (only 5 chars remain).

Example 2

Input: calls = [(2,), (2,), (2,), (2,)] file_content = "wxyz"

Output: [2, 2, 0, 0]

Explanation: First two calls read w and x, then y and z, then file is exhausted.

Constraints

  • 1 <= n <= 1000
  • The file contains at most 10,000 characters
  • The read method may be called multiple times
  • The read4 API reads up to 4 characters from the file into buf4 and returns the number of characters read
Python (current runtime)

Case 1

Input: calls = [(4,), (4,), (4,)] file_content = "mnopqrstuv"

Expected: [4, 4, 2]

Case 2

Input: calls = [(3,), (5,), (2,)] file_content = "abcdefg"

Expected: [3, 4, 0]

Case 3

Input: calls = [(1,), (1,), (1,), (1,), (1,)] file_content = "abc"

Expected: [1, 1, 1, 0, 0]