Hash Map vs Array vs Linked List for Lookup in DSA Python - Complexity Comparison
We want to understand how fast we can find a value in different data structures.
How does the time to look up a value change as the data grows?
Analyze the time it takes to find a value in each data structure.
def lookup_array(arr, target):
for item in arr:
if item == target:
return True
return False
def lookup_linked_list(head, target):
current = head
while current:
if current.value == target:
return True
current = current.next
return False
def lookup_hash_map(hmap, target):
return target in hmap
This code shows how to find a value in an array, a linked list, and a hash map.
Look at what repeats when searching:
- Array and Linked List: Loop through each item one by one.
- Hash Map: Directly check if the key exists using a special method.
- Primary operation: Checking each element one by one for array and linked list; direct key check for hash map.
- How many times: Up to all elements for array and linked list; usually once for hash map.
As the number of items grows, the time to find a value changes differently:
| Input Size (n) | Array/Linked List Operations | Hash Map Operations |
|---|---|---|
| 10 | Up to 10 checks | About 1 check |
| 100 | Up to 100 checks | About 1 check |
| 1000 | Up to 1000 checks | About 1 check |
Pattern observation: Array and linked list grow linearly with input size; hash map stays almost constant.
Time Complexity: O(n) for array and linked list, O(1) for hash map
This means looking up in an array or linked list takes longer as data grows, but hash map lookup stays fast.
[X] Wrong: "All data structures find values equally fast."
[OK] Correct: Arrays and linked lists check items one by one, so they get slower with more data. Hash maps use a special way to jump directly to the value.
Knowing these differences helps you pick the right data structure for fast lookups, a key skill in many coding challenges and real projects.
"What if the hash map has many collisions? How would that affect lookup time complexity?"
Practice
Solution
Step 1: Understand lookup times for each data structure
Hash Map uses a hash function to find keys quickly, usually in constant time O(1). Arrays require scanning or index access, O(1) if index known but O(n) if searching by value. Linked Lists require scanning nodes, O(n).Step 2: Compare average lookup times
Hash Map is fastest on average for key lookup due to direct hashing. Arrays and Linked Lists are slower for searching by value.Final Answer:
Hash Map -> Option AQuick Check:
Fastest lookup = Hash Map [OK]
- Confusing array index access with value lookup
- Thinking linked list lookup is fast
- Assuming stack is a lookup structure
Solution
Step 1: Recall Python syntax for empty data structures
Empty list uses [], empty tuple uses (), empty dictionary uses {}, and empty set uses set().Step 2: Identify the hash map syntax
Hash map in Python is a dictionary, created with {}.Final Answer:
hash_map = {} -> Option AQuick Check:
Empty dict = {} [OK]
- Using [] which creates a list, not a dictionary
- Using () which creates a tuple
- Using set() which creates a set, not a dictionary
arr = [10, 20, 30, 40]
lookup = {val: idx for idx, val in enumerate(arr)}
print(lookup.get(30))
print(lookup.get(50, -1))Solution
Step 1: Understand dictionary comprehension and get method
The dictionary 'lookup' maps values to their indices: {10:0, 20:1, 30:2, 40:3}. lookup.get(30) returns the index for 30, which is 2. lookup.get(50, -1) looks for 50, not found, returns default -1.Step 2: Determine printed output
First print outputs 2. Second print outputs -1.Final Answer:
2 -1 -> Option CQuick Check:
lookup[30] = 2, missing key returns -1 [OK]
- Confusing keys and values in dictionary
- Expecting get to raise error if key missing
- Mixing index and value in output
class Node:
def __init__(self, val):
self.val = val
self.next = None
def find(head, target):
current = head
while current.next is not None:
if current.val == target:
return True
current = current.next
return False
Solution
Step 1: Analyze loop condition in linked list traversal
The loop uses 'while current.next is not None', so it stops before last node. This means the last node's value is never checked.Step 2: Correct loop condition to include last node
Changing to 'while current is not None' ensures all nodes, including last, are checked for target value.Final Answer:
The loop condition should be 'while current is not None' to check last node -> Option BQuick Check:
Loop must check all nodes including last [OK]
- Stopping loop early missing last node
- Adding unnecessary previous pointer
- Thinking recursion is required
Solution
Step 1: Understand lookup needs for large dataset
Checking membership means quickly finding if an element exists. Arrays and linked lists require scanning, O(n) time. Stacks are not designed for membership lookup.Step 2: Identify best data structure for fast membership
Hash Map uses hashing to find elements in average O(1) time, ideal for large datasets and membership checks.Final Answer:
Hash Map because it provides average O(1) lookup -> Option DQuick Check:
Fast membership = Hash Map [OK]
- Choosing array or list for fast lookup
- Confusing insertion speed with lookup speed
- Thinking stack supports membership lookup
Ready to prove it?
Pass the test and this pattern moves unknown
