Why Hash Map Exists and What Problem It Solves in DSA C - Performance Analysis
We want to understand why hash maps are useful by looking at how fast they let us find things.
The question is: How does using a hash map change the time it takes to find or store data?
Analyze the time complexity of the following code snippet.
// Simple search in an array
int linear_search(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // found
}
}
return -1; // not found
}
This code looks for a value by checking each item one by one in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element in the array one by one.
- How many times: Up to n times, where n is the number of items in the array.
As the list gets bigger, the time to find something grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: Doubling the list size roughly doubles the work needed.
Time Complexity: O(n)
This means the time to find something grows directly with the number of items.
[X] Wrong: "Searching in a list is always fast enough, no need for special structures."
[OK] Correct: When the list is large, checking each item one by one takes too long, making programs slow.
Understanding why hash maps exist helps you explain how to make programs faster by avoiding slow searches.
"What if we used a hash map to store items instead of a list? How would the time to find an item change?"
