coding
Lyft
Google
Amazon

Lyft Coding Interview: Persistent Read Wrapper (read4)

Topics:
State Machine
Iterator Design
Simulation
Roles:
Software Engineer
Backend Engineer
SWE Intern
Experience:
Entry Level
Mid Level
Senior

Question Description

You are asked to implement a persistent read wrapper that exposes a read(buf, n) method while internally using a provided read4(buf4) helper that returns up to 4 characters at a time.

Core content

  • You must maintain internal state (a leftover buffer) so that characters returned by read4 but not consumed on one call to read are preserved and returned on subsequent calls. The wrapper's read(buf, n) should write up to n characters into the provided buf and return the number actually written.
  • read4 may return fewer than 4 characters to indicate EOF; your implementation must stop correctly and not attempt extra reads after EOF.

Flow / stages you will follow

  1. On each read call, first drain any leftover characters from your internal buffer into buf until either n is satisfied or leftovers are exhausted.
  2. If more characters are needed, repeatedly call read4 into a temporary 4-char buffer, copy from that buffer into buf up to the remaining needed amount, and store any excess into your internal leftover buffer.
  3. Stop when you have read n characters or read4 returns 0 (EOF).

Skill signals and what interviewers look for

  • Correct stateful design: persisting leftover characters across multiple read calls (iterator/state machine thinking).
  • Correct handling of EOF and partial reads from read4.
  • Proper buffer management and edge-case handling (n = 0, multiple successive reads, final partial chunk).

You should be able to explain the invariant your internal buffer maintains, show example sequences of calls, and reason about time/space complexity. Expect follow-ups about thread-safety, generalizing the chunk size, or adapting the approach for streams or binary data.

Common Follow-up Questions

  • How would you make your Reader thread-safe for concurrent read() calls? What synchronization or lock-free strategies would you use?
  • Generalize the helper: if readK(bufK) reads up to k characters, how does your design change and how do you parameterize the buffer?
  • How would you adapt the wrapper to support peek() or unread() operations (i.e., an iterator with lookahead)?
  • What are the time and space complexity of your solution across multiple successive reads? Can you optimize any aspect for very large n?

Related Questions

1Read N Characters Given read4 (single call) — implement read(buf, n) assuming one call
2Design a buffered reader that supports read, peek, and unread operations
3Implement an iterator over a stream that yields one character at a time with internal buffering

Explore More Questions

Practice This Question with AI

Get real-time hints, detailed requirements, and insightful analysis of the question.

Persistent Read Wrapper (read4) - Lyft Coding Interview | Voker