HashSet and HashMap are hash-based collections designed to provide very fast insertion, deletion, and retrieval operations. Their performance depends on the quality of hash distribution and the number of collisions. In most real-world scenarios, these operations execute in constant time, making them highly efficient for large datasets.
Time Complexity of HashMap
Insertion (put)
O(1)
O(n) before Java 8
O(log n) in Java 8+ when a bucket is converted to a Red-Black Tree
Retrieval (get)
O(1)
O(n) before Java 8
O(log n) in Java 8+ after treeification
Deletion (remove)
O(1)
O(n) before Java 8
O(log n) in Java 8+ after treeification
Time Complexity of HashSet
Since HashSet is internally backed by a HashMap, its performance characteristics are almost identical.
Insertion (add)
O(1)
O(n) before Java 8
O(log n) in Java 8+ after treeification
Retrieval/Search (contains)
O(1)
O(n) before Java 8
O(log n) in Java 8+ after treeification
Deletion (remove)
O(1)
O(n) before Java 8
O(log n) in Java 8+ after treeification
Suppose we store employee IDs in a HashSet.
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Set<Integer> employeeIds =
new HashSet<>();
employeeIds.add(101);
employeeIds.add(102);
employeeIds.add(103);
System.out.println(
employeeIds.contains(102));
employeeIds.remove(102);
}
}true
Why Are Operations Usually O(1)?
1. hashCode() to determine the bucket.
2. equals() to identify the exact object.
This allows direct access instead of traversing all elements.
Impact of Collisions
Bucket 1 → KeyA
Bucket 2 → KeyB
Bucket 3 → KeyC
Operations remain O(1).
KeyA -> KeyB -> KeyC -> KeyD
Search becomes slower because multiple entries must be checked.
KeyB
/ \KeyA KeyD
/
KeyC
Red-Black Trees improve lookup performance to O(log n).
Complexity Summary
A concise interview answer is
HashMap and HashSet provide O(1) average-time complexity for insertion, retrieval, and deletion operations because they use hashing for direct bucket access. In cases of excessive collisions, the worst-case complexity was O(n) before Java 8. From Java 8 onwards, heavily populated buckets are converted into Red-Black Trees, improving the worst-case complexity to O(log n).
Last updated: 11 November 2026
Previous question: How does ConcurrentHashMap improve performance in a multi-threaded environment?
Next question: What is the time complexity of insertion, deletion and retrieval in TreeSet and TreeMap?