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

data-structures

Solution

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.

Problem

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

Original source