> ## 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 Python Solution

> Tested Python solution for LeetCode 157 with 17 pytest cases. Generate a practice environment with lcpy.

LeetCode 157, [Easy](/catalog/easy). 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/description/).

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

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

## Problem

Given a `file` and assume that you can only read the file using a given method `read4`, implement a method to read `n` characters.

**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/0157.Read%20N%20Characters%20Given%20Read4/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 to store characters
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[].
```

**Note:**

* Consider that you cannot manipulate the file directly. The file is only accessible for `read4` but not for `read`.
* The `read` function will only be called once for each test case.
* You may assume the destination buffer array, `buf`, is guaranteed to have enough space for storing `n` characters.

### Examples

```
Input: file = "abc", n = 4
Output: 3
Explanation: After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3.
Note that "abc" is the file's content, not buf. buf is the destination buffer that you will have to write the results to.
```

```
Input: file = "abcde", n = 5
Output: 5
Explanation: After calling your read method, buf should contain "abcde". We read a total of 5 characters from the file, so return 5.
```

```
Input: file = "abcdABCD1234", n = 12
Output: 12
Explanation: After calling your read method, buf should contain "abcdABCD1234". We read a total of 12 characters from the file, so return 12.
```

### Constraints

* `1 <= file.length <= 500`
* `file` consists of English letters and digits.
* `1 <= n <= 1000`

**Note:** 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/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/read_n_characters_given_read4/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
        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)
    # Space: O(1)
    def read(self, buf: list[str], n: int, file: File) -> int:
        i = 0
        buf4 = [""] * 4
        while i < n:
            count = file.read4(buf4)
            if count == 0:
                break
            for j in range(min(count, n - i)):
                buf[i] = buf4[j]
                i += 1
        return i
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags


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