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 4 | Trees <strong>and</strong> Graphs<br />

average of lg n amount of work on each step), or we can be super ma<strong>the</strong>matical:<br />

There are 2^r nodes at level r.<br />

1*2^1 + 2*2^2 + 3*2^3 + 4*2^4 + ... d * 2^d<br />

= sum(r * 2^r, r from 0 to depth)<br />

= 2 (d-1) * 2^d + 2<br />

n = 2^d ==> d = lg n<br />

NOTE: 2^lg(x) = x<br />

O(2 (lg n - 1) * 2^(lg n) + 2) = O(2 (lg n - 1) * n ) = O(n lg n)<br />

Following similar logic, our space complexity is O(n lg n).<br />

CareerCup.com<br />

1 3 2

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

Saved successfully!

Ooh no, something went wrong!