Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: A hash table keyed by short strings uses Java's String.hashCode. Why do some keys collide?

Problem: A hash table keyed by short strings uses Java's String.hashCode. Why do some keys collide?
// String.hashCode: h = 31*h + c over the characters, in 32-bit int arithmetic
System.out.println("Aa".hashCode() + " " + "BB".hashCode() + " " + ("Aa".hashCode() == "BB".hashCode()));
What is printed?
  1. A. 2112 2113 false
  2. B. 2080 2112 false
  3. C. 2112 2112 true
  4. D. 4290 4290 true

Correct answer: C. 2112 2112 true

'A' = 65, 'a' = 97: 31·65 + 97 = 2112; 'B' = 66: 31·66 + 66 = 2112. Different strings, same hash – so hash maps must compare keys with equals() after matching hashes, and adversarial inputs built from such blocks can force many collisions (Java 8+ turns long buckets into trees, O(log n)).

More Coding Interview Problems questions

Exams that ask this topic