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?
- A. Nothing serious: chaining keeps every insert O(1), so the total stays O(n)
- B. Growing the table to m = 2000 buckets spreads the keys over 2 buckets, which fixes the problem
- 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
- 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)).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- An empty queue performs: enqueue 7, enqueue 2, enqueue 9, dequeue, enqueue 4, dequeue. Which element is now at the front?
- In a doubly linked list you are given a pointer to a node X somewhere in the middle. What is the time to delete X?
- A hash table has 7 slots and uses h(k) = k mod 7. In which slot is the key 50 placed if that slot is empty?
- Operators have the usual precedence ( and / above + and −, all left-associative). What is the postfix form of A (B + C) / D − E?
- What is the value of the prefix expression + 3 4 − 9 / 8 2 ?
- Selection sort (find the minimum of the unsorted part, swap it to the front only if it is not already there) sorts [29, 10, 14, 37, 13]…