Saturday, January 28, 2012

Search by first name, last name or both.


Create a structure that will allow you to search a person by first name or last name (or both), in better than O(N) timeframe.


Approach:
Suppose the names are:
String [] names = {
"A B",
"A C",
"A D",
"A Y",
"A Z",
"A X",
"X I",
"X Y",
"X Z",
"X B",
"X C",
"X D",
"I J",
"I L",
"I K",
"Z I"
};


Approach:
1. Create 2 HashMaps, one FMap as Map<firstName, List of FullNames> and another LMap as Map<lastName, list of FullNames>.
2. Now you can search firstname in the FMap or lastName in LMap.
3. If you want to search with fullname then split full name say "F L" into first and last name ie "F" and "L", then search F in FMap
and "L" into LMap and then take the cross of FMap and LMap results.
4. In FMap or LMap, instead of using list to store fullnames, we can use better datastructures like BST or another HashMap which gives better read complexity.


Code output:

Searching with full name ...
[A X]
Searching with first or last name ...
[X I, X Y, X Z, X B, X C, X D, A X]
Searching with first or last name ...
[I J, I L, I K, X I, Z I]

No comments:

Post a Comment