Hashing and Hash Tables
- 75Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is linear search, and how does the number of items affect its search time?
75 questions
- 1
What is linear search, and how does the number of items affect its search time?
Model answer
Linear search examines items one by one until the target is found. As the number of items increases, the required search time generally increases.
Explanation
A randomly arranged library may require examining many books before finding the desired one.
- 2
Define hashing.
Model answer
Hashing is the process of converting a key into a fixed-size value.
Explanation
For example, the string "inside code" can be converted into a numerical hash.
- 3
What is a hash?
Model answer
A hash is the fixed-size value produced when a key is processed by hashing.
Explanation
In the example, hashing the key "inside code" produces the hash value 29.
- 4
What is the purpose of using hashing in a library-like data structure?
Model answer
Hashing calculates the position associated with a key directly, avoiding the need to examine all preceding items.
Explanation
A book title can be hashed to determine the array position where the book should be stored.
- 5
What is a hash table?
Model answer
A hash table is a data structure that stores key/value pairs and uses hashing to calculate the array index of a value.
Explanation
Values are stored in array slots, and the key determines which slot is used.
- 6
In the library analogy, what do the key, value, array, and index represent?
Model answer
The key is the book title, the value is the book, the array is the library, and the index is the book's position.
Explanation
Hashing the title identifies the position associated with the book.
- 7
What condition must be followed when inserting an item into a hash table?
Model answer
The item must be inserted into the position determined by hashing its key.
Explanation
Using the same position during insertion and searching allows the item to be located later.
- 8
What does a hash function do?
Model answer
A hash function takes a key as input, performs computations, and returns the key's hash.
Explanation
The hash function is the mechanism used to perform the hashing process.
- 9
What are the possible output indices of a hash function for a table with m slots?
Model answer
The output must be an integer from 0 through mā1.
Explanation
These values correspond exactly to the valid indices of an array with m slots.
- 10
Why must a hash function be deterministic?
Model answer
A deterministic hash function always returns the same hash for the same key, ensuring that insertion and later searching use the same position.
Explanation
If the hash changed between operations, a search might look in the wrong slot.
- 11
Describe a simple hash function for strings based on ASCII codes.
Model answer
Add the ASCII codes of all characters in the string and return the sum modulo m.
Explanation
The modulo operation produces a result in the valid range from 0 to mā1.
- 12
Using the described hash function, what hash is produced for "inside code" when the ASCII sum is 1079 and m=30?
Model answer
The hash is 1079 mod 30 = 29.
Explanation
Therefore, the associated value is placed at index 29.
- 13
Why can many different hash functions be created?
Model answer
A hash function is simply a computation that maps keys to hash values, and many different computations can perform that mapping.
Explanation
The quality of the resulting function depends on properties such as distribution and efficiency.
- 14
What does it mean for a hash function to distribute keys evenly?
Model answer
It means that the possible hash values are produced with approximately equal probability.
Explanation
Even distribution prevents too many keys from being assigned to the same slots.
- 15
Why does the sum-of-ASCII-codes hash function give the same result for "abc" and "acb"?
Model answer
The function adds character codes without considering order, so every permutation of the same characters has the same sum and hash.
Explanation
This is undesirable because strings with different orders are different keys.
- 16
Why is the sum-of-ASCII-codes function unsuitable for strings of at most 20 alphabetic characters?
Model answer
The maximum possible sum is 20imes122=2440, so the function cannot produce indices greater than 2440 regardless of the table size.
Explanation
Consequently, slots after index 2440 cannot be reached by any key.
- 17
What two properties should a good hash function have?
Model answer
It should distribute keys as evenly as possible and be computationally efficient.
Explanation
These properties reduce collisions and support good overall hash-table performance.
- 18
Define a collision in a hash table.
Model answer
A collision occurs when two different keys produce the same hash value and therefore the same initial index.
Explanation
For example, "Samy Sterious" and "Khaled Anas" both hash to index 14 in the example.
- 19
Why are collisions unavoidable when the key space is larger than the number of table slots?
Model answer
There are only m possible hash values but potentially infinitely many keys, so different keys must eventually share a hash value by the pigeonhole principle.
Explanation
This guarantees collisions when enough distinct keys are inserted.
- 20
Under what condition can a set of keys be stored without collisions?
Model answer
It is possible when the number of keys does not exceed the number of slots and a suitable hash function maps each key to a different slot.
Explanation
For example, 20 known keys can potentially be mapped uniquely into 30 slots.
- 21
What is a perfect hash function?
Model answer
A perfect hash function maps a specified set of keys to table positions without collisions.
Explanation
Perfect hashing is possible for a fixed key set when enough slots and an appropriate function are available.
- 22
Why can a poor hash function create many collisions even when the table has many slots?
Model answer
If the function maps most keys to a small subset of slots, those slots become overloaded while many others remain unused.
Explanation
For example, producing almost all hashes from 0 to 4 in a 30-slot table causes heavy clustering.
- 23
How does increasing the number of slots usually affect collisions?
Model answer
Increasing the number of slots gives keys a larger range of possible indices and can reduce collisions.
Explanation
This benefit depends on the hash function being able to reach and distribute keys across the new slots.
- 24
Why might rehashing fail to reduce collisions when using the simple ASCII-sum function?
Model answer
If the function cannot produce hashes beyond a limited maximum, newly added slots are unreachable and keys remain concentrated in the original range.
Explanation
For the stated string restriction, slots after index 2440 remain empty even after the table grows.
- 25
What is separate chaining?
Model answer
Separate chaining handles collisions by storing a linked list of key/value pairs at each table index.
Explanation
All pairs whose keys hash to the same index are placed in that index's linked list.
- 26
In separate chaining, how are three values with hash 13 stored?
Model answer
They are stored in a linked list of length 3 at index 13, with each node containing one key/value pair.
Explanation
The slot holds the list rather than a single value.
- 27
Why must each node in a separate-chaining list store the key as well as the value?
Model answer
The key identifies which value belongs to the requested item when several values share the same index.
Explanation
Hashing identifies the list, but comparing stored keys identifies the correct node within that list.
- 28
How is a value retrieved using separate chaining after a collision?
Model answer
Hash the requested key, access the linked list at that index, and search the list for the node containing the same key.
Explanation
The value associated with that matching node is then returned.
- 29
What is open addressing?
Model answer
Open addressing handles collisions by keeping one element per slot and probing alternative slots when the initial slot is occupied.
Explanation
Unlike separate chaining, it does not store linked lists in the slots.
- 30
What is probing in an open-addressed hash table?
Model answer
Probing is the process of searching for an alternative slot for insertion or lookup after the initial slot is unavailable.
Explanation
A probing strategy determines which alternative positions are checked.
- 31
How does linear probing resolve a collision?
Model answer
It checks consecutive slots until it finds an empty slot or the requested key.
Explanation
In the example, occupied positions 14, 15, and 16 lead to insertion at empty position 17.
- 32
Why must open addressing also store keys in the table?
Model answer
Keys are needed to determine whether a probed slot contains the particular item being searched for.
Explanation
The value alone does not identify which key produced it.
- 33
What happens to the load ratio n/m in open addressing?
Model answer
Because each slot holds at most one element, n cannot exceed m, so n/m ranges from 0 to 1.
Explanation
A ratio of 0 means the table is empty and 1 means every slot is occupied.
- 34
Why can n/m exceed 1 with separate chaining?
Model answer
Separate chaining allows multiple elements in one slot's linked list, so the number of elements can exceed the number of slots.
Explanation
For example, 50 elements in 20 slots gives a ratio of 2.5.
- 35
What is rehashing?
Model answer
Rehashing creates a new table with more slots and reinserts all previously stored key/value pairs into it.
Explanation
The keys must be inserted again because their indices may change when the table capacity changes.
- 36
Why does rehashing usually reduce collisions?
Model answer
A larger table provides a wider range of possible hash indices, distributing elements across more positions.
Explanation
This reduces the average number of elements competing for each slot when the hash function uses the expanded range.
- 37
Define the load factor.
Model answer
The load factor is the maximum allowed value of the ratio n/m before the table is rehashed.
Explanation
Here, n is the number of stored elements and m is the number of slots.
- 38
When does a hash table with load factor 0.75 rehash?
Model answer
It rehashes as soon as n/m exceeds 0.75.
Explanation
For a table with 100 slots, inserting the 76th element triggers rehashing.
- 39
What is the usual effect of choosing a lower load factor?
Model answer
A lower load factor creates more empty space and fewer collisions, improving time efficiency at the cost of space efficiency.
Explanation
The table uses more slots relative to the number of elements.
- 40
What is the usual effect of choosing a higher load factor?
Model answer
A higher load factor uses space more efficiently but produces more collisions, which can reduce time efficiency.
Explanation
Fewer slots are available relative to the number of stored elements.
- 41
Why might a hash table shrink when it becomes too empty?
Model answer
It may rehash into a smaller table to reduce wasted space.
Explanation
A lower-capacity table can improve space efficiency when the number of stored elements decreases.
- 42
What are the four main pieces of state in the described hash table implementation?
Model answer
They are the capacity, size, load factor, and array of slots.
Explanation
Capacity counts slots, size counts stored elements, the load factor controls rehashing, and the slot array stores the data.
- 43
What does a node contain in the separate-chaining implementation?
Model answer
A node contains a key, a value, and a pointer to the next node in its linked list.
Explanation
The pointer connects nodes that occupy the same hash-table slot.
- 44
What does the linked-list structure contain?
Model answer
It contains the head pointer of the list.
Explanation
The head identifies the first node in the chain.
- 45
How is a node inserted at the beginning of a linked list?
Model answer
Create a node whose next pointer references the current head, then make the new node the head.
Explanation
This avoids traversing the list.
- 46
How does linked-list search work in the implementation?
Model answer
It traverses the nodes and returns the node whose key equals the requested key; if none matches, it returns null.
Explanation
Key comparison is necessary because multiple nodes may share a table index.
- 47
How does linked-list deletion work in the implementation?
Model answer
It finds the node whose successor has the requested key, bypasses that successor, and returns whether deletion occurred.
Explanation
The method returns true when a node is deleted and false when the key is absent.
- 48
What happens during rehashing in the described implementation?
Model answer
The old slots are saved, capacity is doubled, size is reset, a new empty slot array is created, and every old key/value pair is inserted into the new table.
Explanation
Reinsertion recalculates positions using the new capacity.
- 49
How does insertion update an existing key?
Model answer
It hashes the key, searches the corresponding chain, and replaces the existing node's value if the key is found.
Explanation
The size is not increased because no new node is added.
- 50
How does insertion handle a key that is not already present?
Model answer
It creates a new key/value node, inserts it into the appropriate chain, and increments the table size.
Explanation
The load ratio is then checked to determine whether rehashing is necessary.
- 51
How does a lookup operation determine whether a key exists?
Model answer
It hashes the key, searches the linked list at the resulting index, and reports existence if a non-null node is returned.
Explanation
A null search result means the key is absent.
- 52
How does the get operation retrieve a value?
Model answer
It hashes the key, searches the corresponding chain, and returns the matching node's value or null if the key is absent.
Explanation
The key is used to identify the correct node within the chain.
- 53
What size update occurs after deleting a key/value pair?
Model answer
The table size is decremented only if deletion succeeds.
Explanation
A failed deletion does not change the number of stored elements.
- 54
What are examples of built-in hash-table implementations in programming languages?
Model answer
Examples include Python's
dict, Java'sHashMap, and C++'sunordered_map.Explanation
These built-in structures are generally used instead of implementing a general-purpose hash table from scratch.
- 55
What is the time complexity of inserting at the beginning of a linked list?
Model answer
It is O(1).
Explanation
The operation changes pointers without traversing existing nodes.
- 56
What is the time complexity of searching a linked list of length l?
Model answer
It is O(l).
Explanation
The search may need to inspect every node in the list.
- 57
What is the time complexity of deleting from a linked list in the described implementation?
Model answer
It is O(l), where l is the list length.
Explanation
The node must first be located by traversing the list.
- 58
Why is the hash function considered O(1) with respect to the table size?
Model answer
Its runtime does not depend on how many elements are stored in the hash table.
Explanation
Although hashing can depend on key length, fixed-size keys or bounded key lengths make that cost constant in the stated analysis.
- 59
What are the best- and worst-case search times for a chain in a separate-chaining table?
Model answer
The best case is O(1) when the chain has length 0 or 1, while the worst case is O(n) when all n elements are in one chain.
Explanation
The search cost depends on the length of the chain selected by the hash.
- 60
Why do collisions reduce hash-table performance?
Model answer
Collisions create longer chains or longer probe sequences, requiring more nodes or slots to be examined during operations.
Explanation
More elements competing for a position increase search work.
- 61
What is the average-time complexity of searching, getting, and deleting in a well-implemented separate-chaining hash table?
Model answer
Each operation is O(1) on average.
Explanation
A good hash function and suitable resizing keep chain lengths bounded on average.
- 62
Why is hash-table insertion O(1) on average and amortized rather than always O(1)?
Model answer
Normal insertion is constant time on average, but occasional rehashing costs O(n); because rehashing happens infrequently, the average cost over many insertions is O(1) amortized.
Explanation
The expensive resize cost is spread across the many inexpensive insertions between rehashes.
- 63
What is the worst-case time complexity of major hash-table operations?
Model answer
Insertion, lookup, value retrieval, and deletion can all take O(n) in the worst case.
Explanation
This can occur when collisions concentrate many elements in one chain or cause extensive probing.
- 64
What is the space complexity of a hash table?
Model answer
The space complexity is O(n).
Explanation
There are n element nodes, and the number of slots is proportional to n through the load-factor policy.
- 65
Why is a hash table often preferred over a simple array for key/value storage?
Model answer
A hash table provides average constant-time insertion, lookup, value retrieval, and deletion by computing positions from keys.
Explanation
The main advantage described is time efficiency for key-based operations.
- 66
What is a phone agenda's key/value mapping in a hash table?
Model answer
A person's name is the key and the person's phone number is the value.
Explanation
Hashing the name identifies where the phone number is stored.
- 67
How can a hash table implement a word counter?
Model answer
Each word is used as a key, and its value is an integer representing the number of occurrences.
Explanation
The count associated with a word can be updated whenever that word appears.
- 68
How can a hash table implement a dictionary?
Model answer
A word is used as the key and its definition is stored as the value.
Explanation
Hashing the word provides access to its definition.
- 69
How does hashing help solve the two-sum problem in O(n) time?
Model answer
Store each array element and its index, and for each element x, check whether kāx has already been stored; if so, return the two indices.
Explanation
The hash table avoids testing every pair, which would take O(n2) time.
- 70
What is the key/value requirement for uniqueness in a hash table?
Model answer
Keys must be unique, but different keys may have the same value.
Explanation
A repeated key represents the same mapping, whereas repeated values do not create ambiguity between keys.
- 71
Why must a hash-table key be immutable?
Model answer
Changing a key can change its hash, causing the table to search in a different location from the one used when the key was inserted.
Explanation
The same key must always produce the same hash.
- 72
Why can an array or set generally not be used as a hash-table key?
Model answer
Arrays and sets are mutable, so their contents and therefore their hashes can change after insertion.
Explanation
This violates the requirement that a key's hash remain stable.
- 73
Give examples of suitable immutable hash-table keys.
Model answer
Integers, strings, and tuples are examples of immutable keys.
Explanation
Their state does not change in the way required to invalidate their hashes.
- 74
Why may a mutable object be used as a hash-table value?
Model answer
Values are not hashed to determine their storage position, so changing a value does not invalidate the key's location.
Explanation
A value can therefore be an integer, string, array, hash table, or other object.
- 75
Besides hash tables, what is another application of hashing mentioned in the content?
Model answer
Hashing can also be used in cryptography.
Explanation
The discussion focuses on hash tables but notes that hashing has broader applications.

Ask anything
We've read this whole study set, so questions about it get the best answers.