Interview Question


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
1
of 1 vote

We can use a n size queue.
Keep 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.

- Emmkay November 11, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

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?

- CameronWills November 11, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Yes we should free the memory of the front element when removing it from the queue. So, that only n rows are always present in the memory.

- Emmkay November 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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.

- Emmkay November 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

fill an array of n Strings in cyclic way until you reach EOF.
then traverse from the cyclic beggining and print.

e.g. array[i % n] <= read
etc.

- avico81 November 13, 2012 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More