Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suitable data structure for finding a person's phone number, given their name?

Suppose you want to write a program that implements a simple phone book. Given a particular name, you want to be able to retrieve that person's phone number as quickly as possible. What data structure would you use to store the phone book, and why?

like image 501
fcukinyahoo Avatar asked Dec 09 '22 02:12

fcukinyahoo


2 Answers

the text below answers your question.

In computer science, a hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys (e.g., a person's name), to their associated values (e.g., their telephone number). Thus, a hash table implements an associative array. The hash function is used to transform the key into the index (the hash) of an array element (the slot or bucket) where the corresponding value is to be sought.

the text is from wiki:hashtable.

there are some further discussions, like collision, hash functions... check the wiki page for details.

like image 181
Kent Avatar answered Apr 13 '23 01:04

Kent


I respect & love hashtables :) but even a balanced binary tree would be fine for your phone book application giving you in worst case a logarithmic complexity and avoiding you for having good hash functions, collisions etc. which is more suitable for huge amounts of data.

When I talk about huge data what I mean is something related to storage. Every time you fill all of the buckets in a hash-table you will need to allocate new storage and re-hash everything. This can be avoided if you know the size of the data ahead of time. Balanced trees wont let you go into these problems. Domain needs to be considered too while designing data structures, for an example for small devices storage matters a lot.

like image 44
Yavar Avatar answered Apr 12 '23 23:04

Yavar