A Hash table is a Data Structure that provides a mapping from key to values using a technique called hashing. Hashing means a Hash function is used to compute an index (or hash code) for a given key, determining where the value should be stored in an array.
The data is stored as key-value pairs hence key must be unique but no restrictions for values, they can be duplicate.
Note:
General Time complexity analysis:
Hash Function Type | Best Case | Average Case | Worst Case |
---|---|---|---|
Simple Hash (e.g., Modulo Hashing) | |||
Cryptographic Hash (SHA-256, MD5, etc.) | |||
Perfect Hashing | |||
Universal Hashing | (rare collision case) |
Hash Function:
A hash function is a function that maps a key to a whole number in a fixed range.
Properties of Hash function:
If then objects and might be equal, but if then and are certainly not equal.
Deterministic:
Minimized Collisions
Fast Computation
Uniform Distribution
Irreversibility (One-way Function)
Fixed Output Size (Deterministic Size)
Compression
Pre-image Resistance
Second Pre-image Resistance
Collision Resistance
For Example: A function mod maps all interger keys to the range .
A hash function can be defined for an arbitary objects such as String, List, tuples, multi data objects etc.
For a String s let be a hash function defined below where ASCII(x) returns the ASCII value of the character x.
Below hash function take a String and returns numeric hash number in range of .
// Hash function for String
function H(s):
sum := 0
for char in s:
sum = sum + ASCII(char)
return sum % 50
How Hash-table works ?
Hash collision resolution:
We can use one of the many hash collision resolution techniques to handle this.
The two most popular one's are seperate chaining & open addressing.
Seperate chaining:
Open Addressing:
Rehashing
Cuckoo Hashing (Less Common in Java):
Time complexity:
Operation | Average | Worst |
---|---|---|
Insertion | ||
Removal | ||
Search |
Use cases:
Implementation:
Hash-Table Seperate chaining:
Hash-Table Open Addressing:
References: