Buffer Management: Maintain a buffer to store characters read by read7() that weren’t consumed by readN(n) calls.
Reading n Characters: Continuously read using read7() until we have at least n characters in total. If read7() returns fewer than 7 characters, we’ve likely reached the end of the file.
Serve the Required Characters: Serve characters from the buffer to fulfill the readN(n) request.
⏰ Time complexity: O(n)
- Creating and initializing the FileReader and Solution objects themselves are ( O(1) ) operations and do not depend on input size ( n ).
- The main work is done in the readN(int n) method.
Every time read7() is called, it processes up to 7 characters. Therefore, in the worst-case scenario, read7() will be called ( O(\frac{n+6}{7}) = O(\frac{n}{7}) ) times to read n characters.
Each character read by read7() is processed in constant time ( O(1) ).
🧺 Space complexity: O(n)
The buffer is used to store up to 6 unused characters from read7(). Hence, the buffer space is at most 6 characters.
The result string that stores characters read from the buffer and read7() can hold up to n characters.
Other variables such as the StringBuilder and counters (like result, remaining_len) use constant space.