27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 13 | C++<br />

13.1 Write a method to print <strong>the</strong> last K lines of an input file using C++.<br />

pg 76<br />

SOLUTION<br />

One brute force way could be to count <strong>the</strong> number of lines (N) <strong>and</strong> <strong>the</strong>n print from N-10 to<br />

Nth line. But, this requires two reads of <strong>the</strong> file – potentially very costly if <strong>the</strong> file is large.<br />

We need a solution which allows us to read just once <strong>and</strong> be able to print <strong>the</strong> last K lines. We<br />

can create extra space for K lines <strong>and</strong> <strong>the</strong>n store each set of K lines in <strong>the</strong> array. So, initially,<br />

our array has lines 0 through 9, <strong>the</strong>n 1 through 10, <strong>the</strong>n 2 through 11, etc (if K = 10). Each<br />

time that we read a new line, we purge <strong>the</strong> oldest line from <strong>the</strong> array. Instead of shifting <strong>the</strong><br />

array each time (very inefficient), we will use a circular array. This will allow us to always find<br />

<strong>the</strong> oldest element in O(1) time.<br />

Example of inserting elements into a circular array:<br />

Code:<br />

step 1 (initially): array = {a, b, c, d, e, f}. p = 0<br />

step 2 (insert g): array = {g, b, c, d, e, f}. p = 1<br />

step 3 (insert h): array = {g, h, c, d, e, f}. p = 2<br />

step 4 (insert i): array = {g, h, i, d, e, f}. p = 3<br />

1 string L[K];<br />

2 int lines = 0;<br />

3 while (file.good()) {<br />

4 getline(file, L[lines % K]); // read file line by line<br />

5 ++lines;<br />

6 }<br />

7 // if less than K lines were read, print <strong>the</strong>m all<br />

8 int start, count;<br />

9 if (lines < K) {<br />

10 start = 0;<br />

11 count = lines;<br />

12 } else {<br />

13 start = lines % K;<br />

14 count = K;<br />

15 }<br />

16 for (int i = 0; i < count; ++i) {<br />

17 cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!