HardNo. 0158LeetCode Premium

Read N Characters Given read4 II - Call Multiple Times — LeetCode 158 Python Solution

Topics
Array, Interactive, Simulation
Reading time
4 min

The 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.

Example

Example
Parameter:  char[] buf4
    Returns:    int

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

Python solution

PythonSolution
# The read4 API is already defined for you.
# def read4(buf4: List[str]) -> int:


class Solution:
    def __init__(self):
        self.buf4 = [None] * 4
        self.i = self.size = 0

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

Complexity

Time
O(n)
Space · auxiliary
O(1) to O(n)

Related problems

Frequently asked questions

How hard is LeetCode 158. Read N Characters Given read4 II - Call Multiple Times?

LeetCode 158. Read N Characters Given read4 II - Call Multiple Times is rated Hard on LeetCode.

What topics does LeetCode 158. Read N Characters Given read4 II - Call Multiple Times cover?

LeetCode 158. Read N Characters Given read4 II - Call Multiple Times is tagged Array, Interactive and Simulation on LeetCode.

Is LeetCode 158. Read N Characters Given read4 II - Call Multiple Times a premium problem?

Yes. LeetCode 158. Read N Characters Given read4 II - Call Multiple Times is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.