DSA Hashset vs Treeset

FeatureHashSetTreeSet
ImplementationInternally uses a hash table.Internally uses a red-black tree.
OrderingNo order; elements are stored randomly.Maintains ascending order of elements.
DuplicatesDoes not allow duplicate elements.Does not allow duplicate elements.
PerformanceFaster for basic operations like add(), remove(), and contains() (O(1) on average).Slower for basic operations (O(log n)) due to tree traversal.
Null ElementsAllows one null element.Allows one null element (but in case of a comparator, it might throw exception).
Use CaseWhen you need fast lookup and no specific order.When you need elements in sorted order.
Iteration OrderIteration order is not predictable.Iterates in natural order (ascending).
MethodsDoesn’t have methods to handle sorting.Provides methods for range queries, like headSet(), tailSet().
Memory UsageLess memory overhead as it uses a hash table.More memory overhead due to the tree structure.
  1. HashSet:

    • No order of elements.
    • Faster for most operations.
    • Allows null element.
  2. TreeSet:

    • Maintains elements in ascending order.
    • Slightly slower due to sorting.
    • No null if a custom comparator is used.

alt text

leetcode samajhdaar wala approach

alt text

mandabuddhi wala approach

alt text