C++ solution by keeping start/end positions in the buffer

  • 0

    There are 2 cases to handle for the temp buffer

    1. last call read 4 bytes and used only 2, so buffer[2...3] should be the leftover

    2. last call read 3 bytes and used only 1, so buffer[1...2] should be the leftover

    most other solutions use an index an other member variables for tracking the issue, but not very clear to me. I just keep the start/end positions for the leftovers in the buffer, which feels easier to understand. After all, it's all about whether we have leftovers int the buffer or not, and how to track where to copy/how many to copy.

    // Forward declaration of the read4 API.
    int read4(char *buf);
    class Solution {
        char buffer[4];
        int start;
        int end;
        Solution() {
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
        int read(char *buf, int n) {
            if (n==0) {
                return 0;
            int i=0;
            for(int j=start;i<n && start<=end;++j) {
                buf[i++] = buffer[j];
            if (i==n) {
                return i;
            int k =read4(buffer);
            start = 0;
            end = k-1;
            while(i<n && start<=end) {
                buf[i++] = buffer[start++];
                if (start>end) {
                    start = 0;
                    end = k-1;
            return i;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.