I am starting to revise the DSA topics when an idea popped in; how about starting to create one mini project based on each topic while revisiting them? This way it can give me insights into how data structures and algorithms are applied in the real world and also I can have something to showcase.
First Project of This Series: A Phonebook App
Without further ado, here is the first project of my learning series: a Phonebook App. Check the app here: https://hashphonebook.netlify.app/
I made this app some years ago but at that time I used the logic of linear searching. Which is good because it was a demo project and there is no need to store thousands of numbers, so the search can check all the possibilities and then return the desired result.
Initially I stored my contacts in a simple JavaScript Array:
let userArray = [
{ userName: "Jane", number: "1237893457" },
{ userName: "Oscar", number: "4562317895" }
];
And to find a contact I used .find() which loops through the array one by one:
// Time Complexity: O(n) Linear Time
const result = userArray.find(contact => contact.userName === "Oscar");
But Why Is Linear Search Not Enough?
In the real world, the scenario is different. We need to store many numbers in our contact list. For example: we store 100000 numbers and in an emergency case, taking the worst scenario if our phonebook takes O(100000) time to show the result then it is too much in this fast-paced world.
This is where performance actually matters not just whether the app works or not!
Optimizing the Search Logic
So the solution is using something that can give results in a shorter time. I changed the array to a HashMap and searched through the map using the key (username).
This way, the lookup time is much faster (O(1)) and more suitable for real-world use cases. Because A Hashmap acts like a real-world dictionary. You don't read every word to find "Strawberry" you flip straight to S.
let contactMap = {
"Jane": "1237893457",
"Oscar": "4562317895"
};
// Time Complexity: O(1) Constant Time
const number = contactMap["Jane"];
It doesn't matter if I have 5 contacts or 5 billion. The lookup speed is constant.
The Code Refactor
Here is the actual code I changed in my project:
Before (Array.push):
userArray.push({ userName, contactNumber });
After (Map Key-Value):
// Storing as a key-value pair and making the search case-insensitive
contactMap[userName.toLowerCase()] = {
originalName: userName,
number: contactNumber
};
This project made me realize that a "working code" is not always "good code". Linear search was enough for a demo but it doesn't scale and real-world applications demand better solutions.
This is just the first step in my DSA revision journey and I plan to keep building small projects like this!
Top comments (0)