Phone Book (HashMap) - Problem

Implement a simple phone book using a hash map that supports four basic operations:

  • Add Contact: Add a name and phone number to the phone book
  • Search Contact: Find a phone number by name
  • Delete Contact: Remove a contact from the phone book
  • List All Contacts: Display all contacts in the phone book

Your implementation should handle multiple operations efficiently and return appropriate responses for each operation type.

The input will be a list of operations, where each operation is represented as [operation_type, name, phone_number] (phone_number is optional for some operations).

Operations:

  • ["add", "John", "123-456-7890"] - Add John with phone 123-456-7890
  • ["search", "John"] - Search for John's phone number
  • ["delete", "John"] - Delete John from phone book
  • ["list"] - List all contacts

Input & Output

Example 1 — Basic Operations
$ Input: operations = [["add", "John", "123-456-7890"], ["search", "John"], ["add", "Alice", "987-654-3210"], ["list"]]
Output: ["Contact added", "123-456-7890", "Contact added", [["John", "123-456-7890"], ["Alice", "987-654-3210"]]]
💡 Note: Add John with phone 123-456-7890, search returns his number, add Alice, list shows both contacts
Example 2 — Delete Operation
$ Input: operations = [["add", "Bob", "555-1234"], ["delete", "Bob"], ["search", "Bob"]]
Output: ["Contact added", "Contact deleted", "Contact not found"]
💡 Note: Add Bob, delete Bob successfully, searching for Bob returns not found
Example 3 — Empty Phone Book
$ Input: operations = [["search", "Nobody"], ["list"], ["delete", "Nobody"]]
Output: ["Contact not found", [], "Contact not found"]
💡 Note: Search in empty phone book returns not found, list returns empty array, delete returns not found

Constraints

  • 1 ≤ operations.length ≤ 1000
  • Each operation is valid format
  • Names contain only letters and spaces
  • Phone numbers contain digits and dashes

Visualization

Tap to expand
Phone Book with Hash MapINPUT OPERATIONS["add", "John", "123-456-7890"]["search", "John"]["add", "Alice", "987-654-3210"]["list"]4 operations to processHASH MAP PROCESSING1map["John"] = "123-456-7890"2return map["John"]3map["Alice"] = "987-654-3210"4return all key-value pairsHash Table State:"John" --> "123-456-7890""Alice" --> "987-654-3210"O(1) average lookup timeRESULTS ARRAY"Contact added""123-456-7890""Contact added"[["John","123-456-7890"],["Alice","987-654-3210"]]4 results returnedKey Insight:Hash maps provide O(1) average-time operations for phone book CRUD, makinglookups instant regardless of the number of contacts stored.TutorialsPoint - Phone Book HashMap Implementation | Hash Map Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen