156/670

156. Read N Characters Given Read4

Easy

A file can only be accessed through a tiny API called read4: each call copies up to 4 consecutive characters of the file into the 4-slot scratch buffer you hand it and returns how many characters it actually delivered. It returns fewer than 4 only when the file is running out; once the file is exhausted it returns 0.

Using nothing but read4, implement read(buf, n): copy at most n characters of the file into buf (starting at index 0) and return the count you copied. If the file is shorter than n, copy the whole file.

The destination buf is pre-allocated and large enough. In this version read is called exactly once per test, so no state needs to survive between calls.

Example 1:

Input: file = "abc", n = 4

Output: 3 (buf now holds "abc")

Explanation: The caller asked for 4 characters but the file only holds 3, so read copies "abc" and returns 3. Note that the final read4 call delivered fewer than 4 characters.

Example 2:

Input: file = "abcde", n = 3

Output: 3 (buf now holds "abc")

Explanation: read4 hands over "abcd" in one shot, but only 3 characters were requested — the extra d must not be copied into buf.

Constraints:

  • 0 ≤ file.length ≤ 1000
  • 1 ≤ n ≤ 1000
  • The file contains only letters and digits (no whitespace).
  • read is called exactly once per test.

Hints:

read4 moves through the file in blocks of four no matter what you ask for. Two things can end the job: the file runs dry (read4 returns fewer than 4), or you have copied n characters.

n is rarely a multiple of 4, so the last useful read4 call may hand you more than you need. Copy min(returned, n − copied so far) out of the scratch buffer and ignore the rest.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: file = "abc", n = 4

Expected output: 3 (buf = "abc")