00:00

Problem Statement

Input/Output Examples

Visual Explanation

Masking with n - 1 works only because the capacity is a power of two, which is why the table always doubles.

Approaches

Both approaches pass the same 1.8 million random operations against java.util.HashMap. The first chains colliding entries; the second probes for the next free slot.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

With a good hash and a load factor of 0.75, each operation inspects only a few entries on average. A resize costs O(n), but it happens rarely enough that inserts stay O(1) amortised.

Interview Tips and Recommended Approach

  • Explain the threshold: capacity × load factor, so 16 × 0.75 = 12 entries before the first resize.
  • Use equals() after comparing hashes. Equal hashes do not mean equal keys.
  • Mention Java 8 tree bins. HashMap turns a chain of 8 or more into a red-black tree when the table has at least 64 slots.
  • Keys must not change after insertion, or their hash no longer matches their slot.

Recommended Approach: Separate Chaining

Why: it is the design java.util.HashMap uses, removal is trivial and it degrades gracefully when the table fills up.