Revisiting DSA Through Mini Projects #1: Optimizing a Phonebook with HashMap
Source: Dev.to
Introduction
I’m revisiting data structures and algorithms (DSA) by creating a mini‑project for each topic. This approach helps me see how DSA concepts are applied in real applications and gives me something to showcase.
The first project in this series is a Phonebook App – you can try it here: https://hashphonebook.netlify.app/
Initial Implementation (Array + Linear Search)
When I first built the app, I stored contacts in a simple JavaScript array and used linear search:
// Sample data
let userArray = [
{ userName: "Jane", number: "1237893457" },
{ userName: "Oscar", number: "4562317895" }
];
// Linear search (O(n))
const result = userArray.find(contact => contact.userName === "Oscar");
For a demo with only a few entries this works fine, but the time complexity is O(n). If the phonebook grew to, say, 100 000 contacts, the worst‑case lookup would be costly in a real‑world scenario.
Why Performance Matters
In an emergency, waiting for a search that scans thousands of entries is unacceptable. We need a data structure that provides faster lookups.
Optimized Implementation (HashMap / Object)
A hash map (or plain JavaScript object) offers O(1) average‑case lookup time. By using the contact’s name as the key, we can retrieve a number instantly, regardless of the total number of entries.
// HashMap representation
let contactMap = {
"Jane": "1237893457",
"Oscar": "4562317895"
};
// Constant‑time lookup (O(1))
const number = contactMap["Jane"];
The lookup speed remains constant whether we have 5 contacts or 5 billion.
Code Changes
Adding a Contact
Before (Array.push):
userArray.push({ userName, contactNumber });
After (Map key‑value):
// Store as a key‑value pair; make the search case‑insensitive
contactMap[userName.toLowerCase()] = {
originalName: userName,
number: contactNumber
};
Searching
Before (Array.find):
const result = userArray.find(contact => contact.userName === searchName);
After (Object lookup):
const entry = contactMap[searchName.toLowerCase()];
Takeaway
A piece of “working code” isn’t always “good code.” Linear search suffices for tiny demos, but it doesn’t scale. Switching to a hash map makes the phonebook efficient and ready for real‑world use.
This is just the first step in my DSA revision journey, and I’ll continue building small projects to reinforce each concept.