A hash table stores key-value pairs and provides average O(1) time for insert, lookup and delete. It uses a hash function to convert a key into an index (a bucket) in an underlying array. How it works 1. Compute the key's hash code: hash = key.GetHashCode() (C#) or key.hashCode() (Java). 2. Map the hash to a bucket index: index = hash mod capacity (implementations often use bit masking with power-of-two capacities, plus extra mixing of the hash bits). 3. Store or look up the entry in that bucket. Examples: Dictionary<TKey, TValue> and HashSet<T> in C#, HashMap and HashSet in Java, dict and set in Python, Map and objects in JavaScript. Collisions A collision happens when two different keys map to the same bucket. Since there are more possible keys than buckets, collisions are unavoidable, so hash tables need a resolution strategy. 1. Separate chaining - Each bucket holds a list (or another structure) of entries whose keys hash to that bucket. - Lookup: compute the bucket, then search its chain comparing keys with Equals. - Simple and degrades gracefully. Java's HashMap uses chaining and converts long chains (8 or more entries, when the table is large enough) into balanced red-black trees, improving the worst case from O(n) to O(log n). - .NET's Dictionary uses chaining implemented with arrays of entries linked by index (avoiding separate node objects for better memory performance). 2. Open addressing - All entries live directly in the array. On collision, probe for another free slot: - Linear probing: try the next slot (index + 1, + 2...). Cache-friendly but suffers from clustering. - Quadratic probing: try index + 1², + 2², + 3²... to reduce clustering. - Double hashing: the step size comes from a second hash function. - Deletion is trickier (requires tombstone markers so searches continue past deleted slots). - Used by Python's dict and many high-performance hash maps (for example Robin Hood or Swiss-table designs). Load factor and resizing - Load factor = number of entries / number of buckets. - When it exceeds a threshold (Java HashMap default 0.75), the table grows (typically doubles) and rehashes all entries into the new buckets — an O(n) operation that happens rarely, so inserts remain amortised O(1). - Pre-size collections when you know the number of entries (new Dictionary<string, int>(capacity: 10_000)) to avoid repeated resizing. Complexity - Average: O(1) for insert, lookup and delete. - Worst case: O(n) if many keys collide (poor hash function or attacks); O(log n) per bucket with tree-based buckets. Hash function quality and security - A good hash function distributes keys uniformly and is fast. - Hash flooding attacks deliberately send keys that collide; mitigations include randomised hashing (.NET randomises string hashing per process; Python uses randomised SipHash) and tree buckets. Equality and hashing contract - If two keys are equal, their hash codes must be equal. Override Equals and GetHashCode together (C#) or equals and hashCode (Java); records do this automatically. - Do not mutate a key after inserting it into a hash table; its bucket would no longer match, and lookups would fail. Uses - Caches, indexes, counting frequencies, deduplication, symbol tables in compilers, database hash joins and hash indexes, and as a building block for LRU caches (hash map plus linked list). Interview summary: "A hash table maps keys to bucket indexes using a hash function, giving average O(1) operations. Collisions are handled by separate chaining (lists or trees in buckets) or open addressing (probing for free slots). Load factor thresholds trigger resizing and rehashing, and good hash functions plus correct Equals and GetHashCode are essential."
Ravindra Wadile · · 0 likes