Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

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

Explanation

To solve this problem, we need to implement a method int read(char[] buf, int n) that reads data from a file using the read4 API multiple times. The read4 API reads 4 characters at a time and returns the number of characters read. The read method should return the total number of characters read.

We can maintain an internal buffer to store the characters read by read4 but not yet consumed by the read method. We use two pointers bufPtr and bufCnt to keep track of the current position in the buffer and the total number of characters in the buffer respectively.

The algorithm works as follows:

  1. If bufPtr reaches the end of the buffer, we read more characters from the file using read4 and refill the buffer.
  2. We copy characters from the internal buffer to the output buffer buf until either we reach n characters or we exhaust all characters in the internal buffer.
  3. If we reach the end of the file or n characters are read, we return the total number of characters read.
public class Solution extends Reader4 {
    private char[] buffer = new char[4];
    private int bufPtr = 0;
    private int bufCnt = 0;

    public int read(char[] buf, int n) {
        int total = 0;
        boolean eof = false;

        while (!eof && total < n) {
            if (bufPtr == 0) {
                bufCnt = read4(buffer);
            }

            if (bufCnt == 0) {
                eof = true;
            }

            while (total < n && bufPtr < bufCnt) {
                buf[total++] = buffer[bufPtr++];
            }

            if (bufPtr == bufCnt) {
                bufPtr = 0;
            }
        }

        return total;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.