Data Structures & AlgorithmsVery hardProduct company OA

A service stores n = 10⁵ integer keys in a chained hash table with m = 1000 buckets and h(k) = k mod m. An attacker sends keys that are all multiples of 1000. What happens, and which fix actually removes the problem?

  1. A. Nothing serious: chaining keeps every insert O(1), so the total stays O(n)
  2. B. Growing the table to m = 2000 buckets spreads the keys over 2 buckets, which fixes the problem
  3. C. All keys land in bucket 0, so the n inserts cost Θ(n²) ≈ 5·10⁹ comparisons; randomising the hash (a seeded universal hash) restores O(1) expected per operation
  4. D. Using a prime number of buckets such as 997 is enough because then no fixed key pattern can collide

Correct answer: C. All keys land in bucket 0, so the n inserts cost Θ(n²) ≈ 5·10⁹ comparisons; randomising the hash (a seeded universal hash) restores O(1) expected per operation

Insertion into a chain usually checks for an existing key, so the i-th insert scans i − 1 entries: Σ i ≈ n²/2. Doubling m to 2000 still puts multiples of 1000 into only 2 buckets. A prime modulus defeats this particular pattern, but an attacker who knows h can simply send multiples of 997. Only a hash chosen at random at runtime (universal hashing / SipHash-style seeds) makes the expected chain length n/m for every input. Java 8 additionally turns long chains into balanced trees (O(log n)).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic