HardNo. 0158LeetCode Premium
Read N Characters Given read4 II - Call Multiple Times — LeetCode 158 Python Solution
- Topics
- Array, Interactive, Simulation
- Reading time
- 4 min
- Source
- leetcode.com
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
Parameter: char[] buf4
Returns: int
buf4[] is a destination, not a source. The results from read4 will be copied to buf4[].Python solution
# 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 jComplexity
- Time
- O(n)
- Space · auxiliary
- O(1) to O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0495 | Teemo Attacking | Easy |
| 0985 | Sum of Even Numbers After Queries | Medium |
| 1389 | Create Target Array in the Given Order | Easy |
| 1409 | Queries on a Permutation With Key | Medium |
| 1503 | Last Moment Before All Ants Fall Out of a Plank | Medium |
| 1535 | Find the Winner of an Array Game | Medium |
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.