Problem statement

https://leetcode.com/problems/read-n-characters-given-read4/

Solution

The main difficulty to understand how to use existing function read4.

When we run cnt = read4(buf4), then cnt will be number of read symbols and they will be written to buf4 array. Also we need to change directly buf array given to as and in the end return the index in this array where we need to stop.

Complexity

It is just $\mathcal{O}(n)$ for time and $\mathcal{O}(1)$ for space if we do not count answer.

Code

class Solution:
    def read(self, buf, n):
        l, cnt, buf = 0, 4, [''] * 4
        
        while cnt == 4:
            cnt = read4(buf4)
            buf[l:l+cnt] = buf4[:cnt] 
            l += cnt
            
        return min(n, l)