Serve Arbitrary Reads From a Fixed Four-Byte Chunk Reader
Last updated: November 29, 2026
Quick Overview
A storage client only exposes read4(buf), which reads up to 4 bytes from a file into buf and returns the count. Implement read(buf, n) that reads up to n bytes and can be called multiple times on the same file, without losing bytes between calls.
Meta
November 29, 20260
0
0 solved
A storage client only exposes read4(buf), which reads up to 4 bytes from a file into buf and returns the count. Implement read(buf, n) that reads up to n bytes and can be called multiple times on the same file, without losing bytes between calls.
A well-known Meta onsite question about stateful buffered I/O. The single-call version is easy; the interviewer is checking that you keep leftover bytes from a partial read4 chunk across calls and stop exactly at n or end of file.
What the Interviewer Expects
- Explain why a single-call implementation loses bytes on repeated calls
- Keep an internal 4-byte buffer with a read pointer and count
- Drain leftovers before calling read4 again
- Stop at n or when read4 returns fewer than 4 with nothing left
- Discuss thread safety
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Make it safe for concurrent readers.
- Generalize to readK for an arbitrary chunk size.
- How do real buffered readers choose buffer sizes?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Given read4(buf4) that fills up to 4 characters into a list and returns the number read (0 at end of file). Implement read(buf, n) that writes up to n characters into buf and returns how many we...
High-Level Design
The bug in the naive version: if a call needs 1 byte, read4 still reads 4, and the 3 extra bytes vanish. So the reader keeps state: an internal 4-slot buffer self.cache, the number of valid bytes `s...