EasyNo. 0157LeetCode Premium
Read N Characters Given Read4 — LeetCode 157 Python Solution
- Topics
- Array, Interactive, Simulation
- Reading time
- 6 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 to read n characters. Method read4: The API read4 reads four consecutive characters from file, then writes those characters into the buffer array buf4.
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.
@param buf4, a list of characters
@return an integer
def read4(buf4):
# Below is an example of how the read4 API can be called.
file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'
buf4 = [' '] * 4 # Create buffer with enough space to store characters
read4(buf4) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
read4(buf4) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
read4(buf4) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
"""
class Solution:
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Number of characters to read (int)
:rtype: The number of actual characters read (int)
"""
i = 0
buf4 = [0] * 4
v = 5
while v >= 4:
v = read4(buf4)
for j in range(v):
buf[i] = buf4[j]
i += 1
if i >= n:
return n
return iComplexity
- 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 157. Read N Characters Given Read4?
LeetCode 157. Read N Characters Given Read4 is rated Easy on LeetCode.
- What topics does LeetCode 157. Read N Characters Given Read4 cover?
LeetCode 157. Read N Characters Given Read4 is tagged Array, Interactive and Simulation on LeetCode.
- Is LeetCode 157. Read N Characters Given Read4 a premium problem?
Yes. LeetCode 157. Read N Characters Given Read4 is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.