KatInterview

158. Read N Characters Given read4 II - Call Multiple Times

HardSolutions 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 problem is a follow-up to "Read N Characters Given Read4," with the key difference that the read method can be called multiple times. This introduces the need for state management between calls. When we invoke read4, it reads a block of up to 4 characters from a file. If a read(buf, n) call requires fewer characters than what read4 provides, the excess characters must be saved and utilized in subsequent calls to read. This prevents data loss and respects the file pointer's state, which is managed internally by the read4 function.

Solution

Read N Characters Given read4 II - Call Multiple Times in Python

# The read4 API is already defined for you.
# def read4(buf4: List[str]) -> int:

class Solution:
    def __init__(self):
        # Internal buffer to store characters from read4
        self.internal_buf = [''] * 4
        # Pointer to the next character to read from internal_buf
        self.internal_ptr = 0
        # Number of valid characters in internal_buf
        self.internal_count = 0

    def read(self, buf: List[str], n: int) -> int:
        total_read = 0
        # Continue reading until n characters are read or EOF is reached.
        while total_read < n:
            # If the internal buffer is exhausted, call read4 to refill it.
            if self.internal_ptr == self.internal_count:
                self.internal_count = read4(self.internal_buf)
                self.internal_ptr = 0
                # If read4 returns 0, we have reached the end of the file.
                if self.internal_count == 0:
                    break
            
            # Calculate how many characters to copy from the internal buffer.
            chars_to_copy = min(n - total_read, self.internal_count - self.internal_ptr)
            
            # Copy characters from internal buffer to the destination buffer.
            for i in range(chars_to_copy):
                buf[total_read + i] = self.internal_buf[self.internal_ptr + i]
            
            # Update pointers and counters.
            self.internal_ptr += chars_to_copy
            total_read += chars_to_copy
            
        return total_read

Read N Characters Given read4 II - Call Multiple Times in Java

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

public class Solution extends Reader4 {
    // Internal buffer to store characters from read4
    private char[] internal_buf = new char[4];
    // Pointer to the next character to read from internal_buf
    private int internal_ptr = 0;
    // Number of valid characters in internal_buf
    private int internal_count = 0;

    /**
     * @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 total_read = 0;
        // Continue reading until n characters are read or EOF is reached.
        while (total_read < n) {
            // If the internal buffer is exhausted, call read4 to refill it.
            if (internal_ptr == internal_count) {
                internal_count = read4(internal_buf);
                internal_ptr = 0;
                // If read4 returns 0, we have reached the end of the file.
                if (internal_count == 0) {
                    break;
                }
            }

            // Calculate how many characters to copy from the internal buffer.
            int chars_to_copy = Math.min(n - total_read, internal_count - internal_ptr);

            // Copy characters from internal buffer to the destination buffer.
            for (int i = 0; i < chars_to_copy; i++) {
                buf[total_read + i] = internal_buf[internal_ptr + i];
            }
            
            // Update pointers and counters.
            internal_ptr += chars_to_copy;
            total_read += chars_to_copy;
        }
        return total_read;
    }
}

Read N Characters Given read4 II - Call Multiple Times in C++

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

class Solution {
private:
    // Internal buffer to store characters from read4
    char internal_buf[4];
    // Pointer to the next character to read from internal_buf
    int internal_ptr = 0;
    // Number of valid characters in internal_buf
    int internal_count = 0;

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_read = 0;
        // Continue reading until n characters are read or EOF is reached.
        while (total_read < n) {
            // If the internal buffer is exhausted, call read4 to refill it.
            if (internal_ptr == internal_count) {
                internal_count = read4(internal_buf);
                internal_ptr = 0;
                // If read4 returns 0, we have reached the end of the file.
                if (internal_count == 0) {
                    break;
                }
            }

            // Calculate how many characters to copy from the internal buffer.
            int chars_to_copy = std::min(n - total_read, internal_count - internal_ptr);

            // Copy characters from internal buffer to the destination buffer.
            for (int i = 0; i < chars_to_copy; ++i) {
                buf[total_read + i] = internal_buf[internal_ptr + i];
            }
            
            // Update pointers and counters.
            internal_ptr += chars_to_copy;
            total_read += chars_to_copy;
        }
        return total_read;
    }
};

Read N Characters Given read4 II - Call Multiple Times in TypeScript

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

var solution = function(read4: (buf4: string[]) => number) {
    // State variables captured by the closure.
    // Internal buffer to store characters from read4.
    const internal_buf: string[] = new Array(4);
    // Pointer to the next character to read from internal_buf.
    let internal_ptr = 0;
    // Number of valid characters in internal_buf.
    let internal_count = 0;

    /**
     * @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 total_read = 0;
        // Continue reading until n characters are read or EOF is reached.
        while (total_read < n) {
            // If the internal buffer is exhausted, call read4 to refill it.
            if (internal_ptr === internal_count) {
                internal_count = read4(internal_buf);
                internal_ptr = 0;
                // If read4 returns 0, we have reached the end of the file.
                if (internal_count === 0) {
                    break;
                }
            }
            
            // Calculate how many characters to copy from the internal buffer.
            const chars_to_copy = Math.min(n - total_read, internal_count - internal_ptr);
            
            // Copy characters from internal buffer to the destination buffer.
            for (let i = 0; i < chars_to_copy; i++) {
                buf[total_read + i] = internal_buf[internal_ptr + i];
            }
            
            // Update pointers and counters.
            internal_ptr += chars_to_copy;
            total_read += chars_to_copy;
        }
        
        return total_read;
    };
};

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.