[
string
design
]
Leetcode 0158 Read N Characters Given Read4 II - Call multiple times
Problem statement
https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/
Solution
This problem is extension of problem 0157. The difference here is that we need to keep global self.buf
, because on the next call we still can have unused symbols inside. So, we have:
self.buf
is buffer with4
elements.self.curr
is variable that indicates on which index inself.buf
we currently on.self.size
is total number of elements in buffer we have.
Let us consider function read
now:
- We start with
pl = 0
. - Iterate until we have
pl < n
and do the following steps: - If we do not have any more elements in buffer to use, we need to update buffer, using function
read4
. - If we have size of buffer equal to
0
, we break immedietly and returnpl
. - Next, we check how many elements we can take from buffer: no more than
self.size - self.curr
and also no more thann - pl
, so we take minimum of them. - Update
buf
with corresponding elements fromself.buf
, updatepl
andself.curr
. - Check if
self.curr
becomes equal toself.size
: it means that we need to update buffer, so putself.curr = 0
.
Complexity
Time complexity is $\mathcal{O}(m)$, where $m = n_1 + \dots + n_k$, sizes of queries. Space complexity is $\mathcal{O}(1)$.
Code
class Solution:
def __init__(self):
self.buf = [""] * 4
self.curr = 0
self.size = 0
def read(self, buf, n):
pl = 0
while pl < n:
if self.curr == 0: self.size = read4(self.buf)
if self.size == 0: break
k = min(n - pl, self.size - self.curr)
buf[pl:pl+k] = self.buf[self.curr: self.curr + k]
pl += k
self.curr += k
if self.curr == self.size: self.curr = 0
return pl