Skip to main content
LeetCode 158, Hard. Topics: Array, Interactive, Simulation. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 19 parametrized pytest cases, and a playground notebook:

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 four consecutive characters from file, then writes those characters into the buffer array buf4. 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:
Below is a high-level example of how read4 works: read4 example
Method read: By using the read4 method, implement the method read that reads n characters from file and stores them in the buffer array buf. Consider that you cannot manipulate file directly. The return value is the number of actual characters read. Definition of read:

Examples

Constraints

  • 1 <= file.length <= 500
  • file consists of English letters and digits.
  • 1 <= queries.length <= 10
  • 1 <= queries[i] <= 500
Note:
  • The read function may be called multiple times; remember to reset your class variables, as they are persisted across multiple test cases.
  • The destination buffer buf is guaranteed to have enough space for storing n characters.
In this repository the read4 API is provided as the read4(buf4) method of the File class in solution.py, and read receives that File instance as its third argument.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026