How to implement PhoneBook using tries data structure.

Phone Book

krishankant singhal
4 min readJun 1, 2020

Design a data structure to store your contacts: Names of people along with their phone numbers.The data structure should be able to do the following quickly:

  • Add contacts.
  • Lookup the phone number by name.
  • Determine who is calling given their phone number.

To do that:

To implement this we will be using HashMap and Trie data structure. Trie data help us to search and provide suggestion on basis of keystroke entered. Once we select any contact name we can search in hashmap.

Generally search query on a Trie is to determine whether the string is present or not in the trie, but in this case we will find all the strings with each prefix of ‘str’. From a Trie node, visit adjacent Trie nodes and do this recursively until there are no more adjacent. This recursive function will take 2 arguments one as Trie Node which points to the current Trie Node being visited and other as the string which stores the string found so far with prefix as ‘str’.

Each Trie Node stores a boolean variable ‘isLast’ which is true if the node represents end of a contact(word).

User will enter the string character by character and we need to display suggestions with the prefix formed after every entered character.
So one approach to find the prefix starting with the string formed is to check if the prefix exists in the Trie, if yes…

--

--

krishankant singhal
krishankant singhal

Written by krishankant singhal

Angular,Vuejs,Android,Java,Git developer. i am nerd who want to learn new technologies, goes in depth.

Responses (1)