A data structure for a phone book such that it can search a number by name and also search a name by number

后端 未结 5 629
Happy的楠姐
Happy的楠姐 2021-01-12 07:52

Do you know a solution to the following interview question?

Design a data structure for a phone book that can safely and efficiently search a number

5条回答
  •  自闭症患者
    2021-01-12 08:35

    You can use a 36-ary tree (26 for alphabets and 10 for digits) and have links pointing from both an alphabet as well as a digit to the same node. (This won't be a "tree" strictly speaking, but you get the idea). This way you won't get a constant time lookup but you won't have to repeat data and the lookup would still be pretty quick.

    Of course, you'd have to handle collisions, but you'd have to handle them while using hashtables too. Maybe you can use two pointers to point to the next collided node by name and by number.

提交回复
热议问题