Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Collections Deep Dive — List, Set, Map, Queue

How does a HashMap find a value in O(1) on average instead of scanning every entry?

Level II · JuniorCollections Deep Dive — List, Set, Map, Queue
Short answer

It runs the key through hashCode() to get a number, then maps that number to a bucket index (roughly hash modulo capacity, implemented as hash & (capacity - 1)).

Explanation

It goes straight to that one bucket and only checks the few keys living there, comparing with equals(). Because it jumps directly to a bucket instead of scanning all n entries, average lookup is O(1). It degrades toward O(n) only if most keys pile into the same bucket.

Common mistakes
  • Saying lookup is always O(1) — it is O(1) on average, worse with many collisions.
  • Not mentioning that the hash picks the bucket index.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Collections Deep Dive — List, Set, Map, Queue.

Practise free

More on Collections Deep Dive — List, Set, Map, Queue