KatInterview

157. Read N Characters Given Read4

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of the problem is to implement a read(buf, n) function that reads n characters from a file into a buffer. The only way to access the file is through a provided API, read4(buf4), which reads up to 4 characters at a time into a temporary buffer. We need to handle the logic of calling read4 multiple times, copying the correct number of characters to the destination buffer, and stopping when either n characters have been read or the end of the file is reached. The problem states that read will be called only once per test case, which simplifies the implementation as we don't need to maintain state across multiple read calls.

Solution

Read N Characters Given Read4 in Python

"""
The read4 API is already defined for you.

    @param buf4, a list of characters
    @return an integer
    def read4(buf4):

# Below is an example of how the read4 API can be called.
file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'
buf4 = [' '] * 4 # Create buffer with enough space to store characters
read4(buf4) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
read4(buf4) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
read4(buf4) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
"""

class Solution:
    def read(self, buf, n):
        """
        :type buf: Destination buffer (List[str])
        :type n: Number of characters to read (int)
        :rtype: The number of actual characters read (int)
        """
        total_copied = 0
        buf4 = [''] * 4  # Temporary buffer for read4

        while total_copied < n:
            # Read from the file into the temporary buffer.
            chars_read = read4(buf4)

            # If we've reached the end of the file, break.
            if not chars_read:
                break

            # Determine how many characters to copy from buf4 to buf.
            chars_to_copy = min(chars_read, n - total_copied)

            # Copy the characters from buf4 to buf.
            # buf is an output parameter, so we modify it in place.
            buf[total_copied : total_copied + chars_to_copy] = buf4[:chars_to_copy]

            # Update the total number of characters copied so far.
            total_copied += chars_to_copy

        return total_copied

Read N Characters Given Read4 in Java

/**
 * The read4 API is defined in the parent class Reader4.
 *     int read4(char[] buf4);
 */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Number of characters to read
     * @return    The number of actual characters read
     */
    public int read(char[] buf, int n) {
        int totalCopied = 0;
        char[] buf4 = new char[4]; // Temporary buffer for read4

        while (totalCopied < n) {
            // Read from the file into the temporary buffer.
            int charsRead = read4(buf4);

            // If we've reached the end of the file, break.
            if (charsRead == 0) {
                break;
            }

            // Determine how many characters to copy from buf4 to buf.
            int charsToCopy = Math.min(charsRead, n - totalCopied);

            // Copy the characters from buf4 to buf.
            System.arraycopy(buf4, 0, buf, totalCopied, charsToCopy);

            // Update the total number of characters copied so far.
            totalCopied += charsToCopy;
        }
        
        return totalCopied;
    }
}

Read N Characters Given Read4 in C++

/**
 * The read4 API is defined in the parent class Reader4.
 *     int read4(char *buf4);
 */

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Number of characters to read
     * @return    The number of actual characters read
     */
    int read(char *buf, int n) {
        int total_copied = 0;
        char buf4[4];

        while (total_copied < n) {
            // Read from the file into the temporary buffer.
            int chars_read = read4(buf4);

            // If we've reached the end of the file, break.
            if (chars_read == 0) {
                break;
            }
            
            // Determine how many characters to copy from buf4 to buf.
            // It's the minimum of characters read in this call and characters remaining to be read.
            int chars_to_copy = std::min(chars_read, n - total_copied);

            // Copy the characters.
            for (int i = 0; i < chars_to_copy; ++i) {
                buf[total_copied + i] = buf4[i];
            }

            // Update the total number of characters copied so far.
            total_copied += chars_to_copy;
        }
        
        return total_copied;
    }
};

Read N Characters Given Read4 in TypeScript

/**
 * Definition for read4()
 * read4 = function(buf4: string[]): number {
 *     ...
 * };
 */

var solution = function(read4: any) {

    /**
     * @param {string[]} buf Destination buffer
     * @param {number} n Number of characters to read
     * @return {number} The number of actual characters read
     */
    return function(buf: string[], n: number): number {
        let totalCopied = 0;
        const buf4: string[] = new Array(4); // Temporary buffer for read4
        
        while (totalCopied < n) {
            // Read from the file into the temporary buffer.
            const charsRead = read4(buf4);
            
            // If we've reached the end of the file, break.
            if (charsRead === 0) {
                break;
            }
            
            // Determine how many characters to copy from buf4 to buf.
            const charsToCopy = Math.min(charsRead, n - totalCopied);
            
            // Copy the characters.
            for (let i = 0; i < charsToCopy; i++) {
                buf[totalCopied + i] = buf4[i];
            }
            
            // Update the total number of characters copied so far.
            totalCopied += charsToCopy;
        }
        
        return totalCopied;
    };
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.