What does the modulo (%) operation do in hashing? How is it related to indices?
The modulo (%) operation in hashing is used to turn a large hash value into a valid array index where the hash table's data is stored.
How it works
- The hash function returns an integer, sometimes a very large one.
- The table has a limited size
N(for example, 100 slots). - To "fit" the hash into the index range
[0 ... N-1], we compute:
javascript
index = hash(key) % N- The result is an index, the position in the array where the element will be placed.
Example
javascript
hash("dog") = 123456
N = 10
index = 123456 % 10 = 6So the element with key "dog" lands in slot #6.
Why the modulo specifically
%gives an even distribution across the index range;- it guarantees that the index never goes out of the array's bounds.
Summary
The modulo operation ties the "abstract" hash to a specific storage location in the table: it turns the hash into a real array index where the data lives.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.