Skip to main content

Why is a perfect hash function impossible in practice?

A perfect hash function is one that produces unique, collision-free hashes for all possible keys and distributes them evenly across the table.

In practice this is impossible, because:

  1. There are infinitely many keys, but a limited number of slots.
  • The table has a finite size N, while the number of possible inputs (strings, numbers, objects) is practically infinite.
  • So different keys will inevitably land in the same slot.
  1. A hash function is a trade-off between speed and uniformity.
  • To be fast, it must work simply (arithmetic operations, bit shifts).
  • But simplicity makes a perfectly even distribution impossible.
  1. Data is unpredictable.
  • It is impossible to know in advance exactly which keys will be used, so it is impossible to build a universal "perfect" function.
  1. Any range restriction (via % N) creates overlaps.
  • Even if hashes are unique in a 64-bit space, once reduced to the table's range (for example, 0-999), collisions will still appear.

Conclusion

A perfect hash function exists only for a known, fixed set of keys in advance. For all other cases, approximations are used: functions that minimize collisions but cannot eliminate them completely.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.