# Python solution with detailed explanation

• Solution

General Idea

• Observe how we pre-allocate buffers here.
• Only thing to be clear is that we cannot use append on buffer, since it is pre-allocated.
• Note n is the maximum number of characters that need to be read. Therefore count != n alone is not a valid terminal condition. We return the characters read which would be less than n. We store the output in buffer.
``````class Solution1(object):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
count, MAX_CHARS = 0, 4
temp = [""]*MAX_CHARS
while True:
if count + x > n: # Assume n=10 and count = 9. x can be anything from 1 to 4. We need to reda 10-9 more characters.
for i in range(n-count):
buf[count], count = temp[i], count + 1
break
elif x < 4:
for i in range(x):
buf[count], count = temp[i], count + 1
break
else:
for i in range(4):
buf[count], count = temp[i], count + 1
return count
``````
``````class Solution(object):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
count, MAX_CHARS = 0, 4
self.temp = [""]*MAX_CHARS
while True:
# Assume n=10 and count = 9. x can be anything from 1 to 4. We need to read 10-9 more characters.
add_char = n-count if count + x > n else x
buf[count], count = self.temp[i], count + 1
if x < MAX_CHARS or count == n:
break
return count
``````
``````class Solution(object):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
count, self.temp = 0, [""]*4
while count != n: