Phone Directory
Learn this problemProblem statement
Implement a bidirectional phone directory that supports name-to-phone and phone-to-name lookups.
The directory supports adding an entry, looking up by phone, looking up by name, removing by name, and removing by phone.
Each operation is a string array:
["ADD", name, phone]: add or update the directory entry. A name can have at most one phone number, and a phone number can belong to at most one name. If the new name or phone already exists, remove the old conflicting mapping before storing the new pair. This operation produces no output.["GET_NAME", phone]: append the associated name, or""if the phone number is absent.["GET_PHONE", name]: append the associated phone number, or""if the name is absent.["REMOVE_NAME", name]: remove the entry for that name and append"true"if an entry was removed, otherwise append"false".["REMOVE_PHONE", phone]: remove the entry for that phone number and append"true"if an entry was removed, otherwise append"false".
Return all appended outputs in order.
What the interview report shared
The report shared the phone-directory class shape and the five operations above. It also showed that updates should keep the two maps in sync when an existing name or phone number is overwritten.
The shared code appeared to have a small typo in remove_by_phone; the intended behavior is the same as remove_by_name: remove the entry from both directions.
Function
processPhoneDirectory(operations: String[][]) → String[]Examples
Example 1
operations = [["ADD","Alice","111"],["ADD","Bob","222"],["GET_NAME","111"],["GET_PHONE","Bob"],["REMOVE_PHONE","111"],["GET_PHONE","Alice"]]return = ["Alice","222","true",""]111 belongs to Alice and Bob's phone is 222. Removing phone 111 deletes Alice's reverse mapping, so the final lookup by Alice returns an empty string.
Example 2
operations = [["ADD","Alice","111"],["ADD","Alice","333"],["GET_NAME","111"],["GET_PHONE","Alice"],["ADD","Bob","333"],["GET_PHONE","Alice"],["GET_NAME","333"]]return = ["","333","","Bob"]Updating Alice from 111 to 333 removes the old phone lookup. Adding Bob with 333 then removes Alice's mapping because a phone number can belong to only one name.