R – implement a telephone address book – reverse index

data structureslanguage-agnostic

Now I am trying to come up with a data structure for implementing a telephone adreess book.
Say there are two infos : name, telephone numbers. The same name can have more than one number.
Now i would like to come up with a data structure that will help me in fetching the number given a name and fetching the name, given a number. I have to do this in the least possible time.
I was thinking of maintaining a map (name to number) and then for a given number somehow reverse index into this map and then find the name.
I am not really sure whats the best way to do this.
Can you suggest an ideal data structure. Will using some reverse index help. If yes then how do i use it in this context.

Best Answer

I would maintain two (hash) maps.

The first map would have Names as the keys, and Sets (or lists or vectors) as the values, this list would contain all of the phone numbers for a specific person.

Map<String,Set<String>> NamesToNumbers;

The second map would have Phone Numbers as the keys, and Names as the values.

Map<String,String> NumbersToNames;

Additionally I would create a simple class with these two maps as private members, the purpose of this class would be to keep the two maps in sync, and pass all put(), remove(), etc. calls to both maps in the correct Key/Value format.

Psuedo code for how id write a put() method in the simple class:

public void put(String Name,String PhoneNumber)
{

Set NumbersForName = NamesToNumbers.get(Name);
if (NumbersForName == null)
  {
    NumbersForName = new Set();
    NamesToNumbers.put(Name,NumbersForName);
  }

NumbersForName.put(PhoneNumber);
NumbersToNames.put(PhoneNumber,Name);  

}

The cost of a look up will be O(1), and the cost of an insertion will be O(1) unless there is a hash collision.

If you are using Java 5+ you should check out Google Collections, they have a nifty Bi-map class which is essentially what I am trying to describe.