Problem Description
Implement a function read(buf, n) that reads n characters from a file. The only available API to read data from the file is read4, which reads 4 consecutive characters at a time. Note that read may be called multiple times, so you need to persist between calls any extra characters read from read4.
Key Insights
- Persist extra characters read from read4 using a class variable.
- Use an intermediate buffer (of size 4) to store characters from read4.
- Maintain pointers to track current position in the extra buffer.
- When read is called, first consume the leftover characters.
- If additional characters are required, keep calling read4 until n characters are read or the file ends.
Space and Time Complexity
Time Complexity: O(n) per call in the worst-case where n characters are requested. Space Complexity: O(1) extra space as the auxiliary buffer is of fixed size 4.
Solution
We use a leftover buffer (and two pointers indicating the current index and the count of characters available) to save any extra characters retrieved by read4 that haven't been requested yet. In each call to read, we exhaust these leftover characters first. If more characters are needed, we repeatedly call read4 until we either fill the destination buffer or run out of characters (indicating the end of the file). This design allows the function to be used across multiple calls while maintaining the file reading state.