<aside>

This section is part of the 5-hour LeetCode DSA Foundations course by Mukul Raina

SLIDE 40: Section Intro, Hash Maps and Hash Sets

Section 5: Hash Maps and Hash Sets

Hash maps and hash sets are the single most important tool for optimizing brute force solutions in interviews. Whenever your brute force uses a nested loop where the inner loop searches for a matching element, a hash map can almost always replace that inner scan with an O(1) lookup, dropping the total complexity from O(n^2) to O(n).

Recognition Signals

You should reach for a hash map or hash set when you see any of these in a problem: need to check if an element exists in a collection, need to count how many times each element appears, need to associate data with a key for fast retrieval, or your brute force has nested loops where the inner loop is searching for a match.

What We’ll Cover

  1. How hashing works and operation costs
  2. The Two Sum pattern and its generalizations
  3. Frequency counting and grouping
  4. Deduplication, existence checking, and lookup optimization
  5. Contains Duplicate II as a combined worked example

Connection to Other Sections

Character frequency maps from Section 4 are hash maps applied to characters. The same int[26] technique is a specialized hash map with a perfect hash function. Two Sum can also be solved with two pointers on sorted input (Section 6), but the hash map approach works on unsorted input without modifying the array. Sliding window problems in Section 7 often use a hash map or hash set internally to track window state.

<aside>

Mukul Raina | youtube.com/@mukulraina | linkedin.com/in/mukulraina

</aside>


SLIDE 41: How Hashing Works and Operation Costs

A hash map stores key-value pairs. Internally, it computes a hash code from the key, maps that to a bucket index, and stores the entry in that bucket. When two different keys produce the same bucket index, a collision occurs. Java’s HashMap handles collisions by chaining entries in the same bucket (using a linked list, upgraded to a balanced tree at 8+ entries per bucket).