/* Lookup time complexities */ #include <stdio.h> int main() { printf("Array lookup: O(1)\n"); printf("Linked List lookup: O(n)\n"); printf("Hash Map lookup: O(1) average, O(n) worst\n"); return 0; }
Arrays allow direct access by index, so lookup is O(1). Linked lists require traversal, so lookup is O(n). Hash maps use hashing for average O(1) lookup but can degrade to O(n) if many collisions occur.
Hash maps provide average O(1) lookup time by using a hash function to find keys quickly. Arrays require index or linear search, and linked lists require traversal.
Linked lists store elements scattered in memory and you must check each node from the start until you find the value, making lookup O(n). Arrays store elements contiguously and allow direct index access.
#include <stdio.h> #include <string.h> int hash(char *key) { return strlen(key) % 3; // simple hash function } int main() { char *keys[] = {"cat", "dog", "bear", "eagle"}; int buckets[3] = {0}; for (int i = 0; i < 4; i++) { int h = hash(keys[i]); buckets[h]++; } printf("Bucket counts: %d %d %d\n", buckets[0], buckets[1], buckets[2]); return 0; }
Keys and lengths: cat(3)%3=0, dog(3)%3=0, bear(4)%3=1, eagle(5)%3=2. Bucket 0 gets cat and dog (collision), bucket 1 gets bear, bucket 2 gets eagle. Output: Bucket counts: 2 1 1. In a real hash map, collisions in a bucket would require linear search within the bucket, impacting lookup time.
Hash maps provide fast lookup and insertion but do not maintain order. Linked lists maintain order but have slow lookup. Combining a hash map with a doubly linked list allows fast lookup and ordered traversal.
