25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 20 | Hard<br />

20 6 Describe an algorithm to find <strong>the</strong> largest 1 million numbers in 1 billion numbers Assume<br />

that <strong>the</strong> computer memory can hold all one billion numbers<br />

SOLUTION<br />

Approach 1: Sorting<br />

CareerCup com<br />

pg 91<br />

Sort <strong>the</strong> elements and <strong>the</strong>n take <strong>the</strong> first million numbers from that Complexity is O(n log n)<br />

Approach 2: Max Heap<br />

1 Create a Min Heap with <strong>the</strong> first million numbers<br />

2 For each remaining number, insert it in <strong>the</strong> Min Heap and <strong>the</strong>n delete <strong>the</strong> minimum<br />

value from <strong>the</strong> heap<br />

3 The heap now contains <strong>the</strong> largest million numbers<br />

4 This algorithm is O(n log m), where m is <strong>the</strong> number of values we are looking for<br />

Approach 3: Selection Rank Algorithm (if you can modify <strong>the</strong> original array)<br />

Selection Rank is a well known algorithm in computer science to find <strong>the</strong> ith smallest (or<br />

largest) element in an array in expected linear time The basic algorithm for finding <strong>the</strong> ith<br />

smallest elements goes like this:<br />

» Pick a random element in <strong>the</strong> array and use it as a ‘pivot’ Move all elements smaller than<br />

that element to one side of <strong>the</strong> array, and all elements larger to <strong>the</strong> o<strong>the</strong>r side<br />

» If <strong>the</strong>re are exactly i elements on <strong>the</strong> right, <strong>the</strong>n you just find <strong>the</strong> smallest element on<br />

that side<br />

» O<strong>the</strong>rwise, if <strong>the</strong> right side is bigger than i, repeat <strong>the</strong> algorithm on <strong>the</strong> right If <strong>the</strong> right<br />

side is smaller than i, repeat <strong>the</strong> algorithm on <strong>the</strong> left for i – right size()<br />

Given this algorithm, you can ei<strong>the</strong>r:<br />

» Tweak it to use <strong>the</strong> existing partitions to find <strong>the</strong> largest i elements (where i = one million)<br />

» Or, once you find <strong>the</strong> ith largest element, run through <strong>the</strong> array again to return all elements<br />

greater than or equal to it<br />

This algorithm has expected O(n) time<br />

2 8 6

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

Saved successfully!

Ooh no, something went wrong!