Hash Tables & Sets

intermediate30 min

Hash Table Basics

A hash table stores key–value pairs. In Java, HashMap and HashSet give average O(1) insert, delete, and lookup—exactly what you need when the statement asks “have we seen this before?”

HashMap in Java

HashSet in Java

A HashSet is a collection that contains no duplicate elements. It’s implemented using a hash table and provides O(1) average time complexity for add, remove, and contains operations.

HashSet Operations

Common Applications

  • Duplicate Detection: Find duplicates in arrays
  • Two Sum: Find pairs that sum to target
  • Anagram Detection: Check if strings are anagrams
  • Subarray Sum: Find subarrays with given sum
  • Union/Intersection: Set operations
  • Frequency Counting: Count occurrences of elements

Two Sum Example