Interview Question
Country: India
Interview Type: In-Person
What about the memory limitations? Perhaps you could flush 'chunks' of the queue to disk, deleting old chunks when they're no longer needed.
Another approach is you could iterate through the file first counting the number of lines. Then process the file knowing at which point in the file to start writing lines to the screen?
One more approach will be similar to printing the last n node of a single linked list. Use 2 file pointers(fp1 and fp2). Move the first pointer(fp1) n rows or till the end-of-file whichever comes first. If there are more that n lines in the file then start moving the 2 file pointers till fp1 reaches the end of file. Once fp2 reaches end of file, then move fp1 till the end of file printing every line and this gives the last n lines in the file.
We can use a n size queue.
- Emmkay November 11, 2012Keep filling the queue. Once the queue is full then keep adding the next lines and remove the front element from the queue at the same time.
So, at any instance the queue will give the last n rows read from the file.