Hash Table Concept and Hash Functions in DSA Java - Time & Space Complexity
We want to understand how fast a hash table can find or store data using a hash function.
The question is: how does the time to do these operations change as we add more items?
Analyze the time complexity of the following code snippet.
public class SimpleHashTable {
private String[] table;
private int size;
public SimpleHashTable(int size) {
this.size = size;
table = new String[size];
}
private int hash(String key) {
return Math.abs(key.hashCode()) % size;
}
public void put(String key, String value) {
int index = hash(key);
table[index] = value;
}
public String get(String key) {
int index = hash(key);
return table[index];
}
}
This code stores and retrieves values using a hash function to find an index in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Computing the hash code and accessing the array index.
- How many times: Each put or get operation does this once per call.
Each operation does a fixed amount of work regardless of how many items are stored.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 hash calculation + 1 array access |
| 100 | 1 hash calculation + 1 array access |
| 1000 | 1 hash calculation + 1 array access |
Pattern observation: The time stays about the same no matter how many items are stored.
Time Complexity: O(1)
This means each lookup or insert takes about the same time, no matter how many items are in the table.
[X] Wrong: "Hash tables always take longer as more items are added because the array gets bigger."
[OK] Correct: The array size is fixed or resized smartly, and the hash function jumps directly to the right spot, so time stays constant on average.
Knowing how hash tables work and why they are fast helps you explain and choose the right data structure in real problems.
"What if the hash function causes many keys to land in the same spot? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of a hash function
A hash function takes a key and transforms it into an index number that points to a location in the hash table.Step 2: Compare options with the hash function role
Only To convert a key into an index for storing values describes converting a key into an index, which is the main purpose of a hash function.Final Answer:
To convert a key into an index for storing values -> Option CQuick Check:
Hash function = key to index [OK]
- Thinking hash functions sort keys
- Confusing hashing with encryption
- Believing hash functions count elements
Solution
Step 1: Identify correct class names and syntax
Java's standard hash table class is HashMap (case-sensitive). Hashtable is also valid but legacy and requires type parameters.Step 2: Check each option's syntax
HashMap map = new HashMap<>(); uses correct generic syntax with HashMap. Hashtable map = new Hashtable(); misses generics. HashTable map = new HashTable<>(); uses wrong class name 'HashTable' (capital T). HashMap map = new HashMap(); reverses generic placement incorrectly.Final Answer:
HashMap map = new HashMap<>(); -> Option BQuick Check:
Correct Java HashMap syntax = HashMap map = new HashMap<>(); [OK]
- Using wrong class name 'HashTable'
- Omitting generics for type safety
- Incorrect generic syntax placement
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.put("apple", 30);
System.out.println(map.get("apple"));
}
}Solution
Step 1: Understand put() behavior in HashMap
When a key already exists, put() replaces the old value with the new one.Step 2: Trace the put() calls for key "apple"
First put("apple", 10) adds key with value 10. Second put("apple", 30) replaces value 10 with 30.Final Answer:
30 -> Option AQuick Check:
Last value for "apple" = 30 [OK]
- Assuming values accumulate instead of overwrite
- Confusing keys and values
- Expecting null for existing keys
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
System.out.println(map.get("1"));
}
}Solution
Step 1: Check key types used in HashMap and get()
The HashMap is declared with Integer keys. The get() method is called with a String "1" instead of Integer 1.Step 2: Understand type mismatch effect
Since keys are Integer, get("1") returns null because "1" (String) is not equal to 1 (Integer).Final Answer:
Using wrong key type in get() method -> Option DQuick Check:
Key type mismatch causes null result [OK]
- Passing String key instead of Integer
- Ignoring type safety warnings
- Assuming automatic type conversion
Solution
Step 1: Analyze the key range and hash function outputs
Keys range from 1000 to 9999. Using modulo 10 (hash(key) = key % 10) gives only 10 buckets, causing many collisions. Modulo 10000 (hash(key) = key % 10000) returns the key itself, which is too large for typical table size. Division by 1000 (hash(key) = key / 1000) gives values 1 to 9, only 9 buckets, too small.Step 2: Evaluate modulo 100 (hash(key) = key % 100)
Modulo 100 gives values from 0 to 99, creating 100 buckets. This spreads keys better and reduces collisions compared to options A and C.Final Answer:
hash(key) = key % 100 -> Option AQuick Check:
More buckets (100) reduce collisions best [OK]
- Choosing too few buckets causing collisions
- Using modulo equal to key range (too large)
- Using division that reduces bucket count too much
Ready to prove it?
Pass the test and this pattern moves unknown
