25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

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.

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

13 2 Compare and contrast a hash table vs an STL map How is a hash table implemented?<br />

If <strong>the</strong> number of inputs is small, what data structure options can be used instead of<br />

a hash table?<br />

SOLUTION<br />

Compare and contrast Hash Table vs. STL map<br />

CareerCup com<br />

pg 76<br />

In a hash table, a value is stored by applying hash function on a key Thus, values are not<br />

stored in a hash table in sorted order Additionally, since hash tables use <strong>the</strong> key to find <strong>the</strong><br />

index that will store <strong>the</strong> value, an insert/lookup can be done in amortised O(1) time (assuming<br />

only a few collisions in <strong>the</strong> hashtable) One must also handle potential collisions in a<br />

hashtable<br />

In an STL map, insertion of key/value pair is in sorted order of key It uses a tree to store<br />

values, which is why an O(log N) insert/lookup is required There is also no need to handle<br />

collisions An STL map works well for things like:<br />

» find min element<br />

» find max element<br />

» print elements in sorted order<br />

» find <strong>the</strong> exact element or, if <strong>the</strong> element is not found, find <strong>the</strong> next smallest number<br />

How is a hash table implemented?<br />

1 A good hash function is required (e g : operation % prime number) to ensure that <strong>the</strong><br />

hash values are uniformly distributed<br />

2 A collision resolving method is also needed: chaining (good for dense table entries),<br />

probing (good for sparse table entries), etc<br />

3 Implement methods to dynamically increase or decrease <strong>the</strong> hash table size on a given<br />

criterion For example, when <strong>the</strong> [number of elements] by [table size] ratio is greater<br />

than <strong>the</strong> fixed threshold, increase <strong>the</strong> hash table size by creating a new hash table and<br />

transfer <strong>the</strong> entries from <strong>the</strong> old table to <strong>the</strong> new table by computing <strong>the</strong> index using<br />

new hash function<br />

What can be used instead of a hash table, if <strong>the</strong> number of inputs is small?<br />

You can use an STL map Although this takes O(log n) time, since <strong>the</strong> number of inputs is<br />

small, this time is negligible<br />

2 1 6

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

Saved successfully!

Ooh no, something went wrong!