> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Read N Characters Given read4 II - Call

> Tested Python solution for LeetCode 158 with 19 pytest cases. Generate a practice environment with lcpy.

LeetCode 158, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Interactive](/catalog/topics/interactive), [Simulation](/catalog/topics/simulation). [View on LeetCode](https://leetcode.com/problems/read-n-characters-given-read4-ii/description/).

Generate this problem as a practice environment: tested reference solution, 19 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 158   # by problem number
lcpy gen -s read_n_characters_given_read4_ii   # by problem name
```

## 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:**

```
    Parameter:  char[] buf4
    Returns:    int

buf4[] is a destination, not a source. The results from read4 will be copied to buf4[].
```

Below is a high-level example of how `read4` works:

![read4 example](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0158.Read%20N%20Characters%20Given%20read4%20II%20-%20Call%20Multiple%20Times/images/157_example.png)

```
File file("abcde"); // File is "abcde", initially file pointer (fp) points to 'a'
char[] buf4 = new char[4]; // Create buffer with enough space
read4(buf4); // read4 returns 4. Now buf4 = "abcd", fp points to 'e'
read4(buf4); // read4 returns 1. Now buf4 = "e", fp points to end of file
read4(buf4); // read4 returns 0. Now buf4 = "", fp points to end of file
```

**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:**

```
    Parameters:  char[] buf, int n
    Returns:     int

buf[] is a destination, not a source. You will need to write the results to buf[].
```

### Examples

```
Input: file = "abc", queries = [1,2,1]
Output: [1,2,0]
Explanation:
sol.read(buf, 1); // buf should contain "a". We read a total of 1 character from the file, so return 1.
sol.read(buf, 2); // Now buf should contain "bc". We read a total of 2 characters, so return 2.
sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.
```

```
Input: file = "abc", queries = [4,1]
Output: [3,0]
Explanation:
sol.read(buf, 4); // buf should contain "abc". We read a total of 3 characters, so return 3.
sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0.
```

### 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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/read_n_characters_given_read4_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/read_n_characters_given_read4_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class File:
    # Test-harness API: backs the read4 interface with the file content
    def __init__(self, content: str) -> None:
        self.content = content
        self.pos = 0

    def read4(self, buf4: list[str]) -> int:
        # Reads up to 4 consecutive characters into buf4 and returns the
        # number of characters actually read; read4 keeps its own file
        # pointer across calls
        chunk = self.content[self.pos : self.pos + 4]
        self.pos += len(chunk)
        for i, char in enumerate(chunk):
            buf4[i] = char
        return len(chunk)


class Solution:
    # Time: O(n) per read call
    # Space: O(1), the internal 4-character buffer is reused across calls
    def __init__(self) -> None:
        self.buf4: list[str] = [""] * 4
        self.i = 0  # next unread position inside buf4
        self.size = 0  # number of valid characters currently in buf4

    def read(self, buf: list[str], n: int, file: File) -> int:
        count = 0
        while count < n:
            if self.i == self.size:
                self.size = file.read4(self.buf4)
                self.i = 0
                if self.size == 0:
                    break
            while count < n and self.i < self.size:
                buf[count] = self.buf4[self.i]
                self.i += 1
                count += 1
        return count
```

## Complexity

| Time | Space |
| - | - |
| O(n) per read call | O(1), the internal 4-character buffer is reused across calls |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.