Read N Characters Given read4 II - Call Multiple Times — LeetCode 158 Python Solution
HardLeetCode PremiumArrayInteractiveSimulation
- Problem
- #158
- 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
Python
# 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Related problems
LeetCode 495Teemo AttackingEasyLeetCode 985Sum of Even Numbers After QueriesMediumLeetCode 1389Create Target Array in the Given OrderEasyLeetCode 1409Queries on a Permutation With KeyMediumLeetCode 1503Last Moment Before All Ants Fall Out of a PlankMediumLeetCode 1535Find the Winner of an Array GameMedium
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.