views:

118

answers:

2

What Data Structure could I use to find the Phone number of a person given the person's name?

+1  A: 

An associative array, such as a hashtable.

Really, anything that maps keys to values. The specific data structure will depend on the language you are using (unless you want to implement your own, in which case you have free reign).

danben
Every time I have to open a real physical phone book (quite rare these days) I'm amazed at the O(log n) process I have to go through to find what I want. If the book were a hash table, instead of a huge sorted array, access would be O(1). The names would only *appear* to be in a completely random order.
Jason Orendorff
+1  A: 

Assuming you will only ever query using the person's name, the best option is to use an associative data structure. This is basically a data structure, usually implemented as a hashtable or a balanced binary search tree, that stores data as key=>value (or, stated in another way, as (key,value) pairs). You query the data structure by using the key and it returns the corresponding value. In your case, the key would be the name of the person and the value would be the phone number.

Rather than implementing a hashtable or a binary search tree for this yourself, check to see if your language has something like this already in its library, most languages these days do. Python has dict, perl has hashes, Java and C# has Map, and C++ has the STL map.

Things can get a little trickier if you have several values for the same key (e.g. the same person having multiple phone numbers), but there are workarounds like using a list/vector as the value, or using a slightly different structure that supports multiple values for the same key (e.g. STL multimap). But you probably don't need to worry about that anyway.

MAK