📊 We use cookies & analytics to improve your experience. Learn more
Latest

Interview DSA Crash Course Module 2 · Lesson 6 of 15

0% Exit to course

Module 2 · Arrays, strings and hashing Lesson 6 of 15

Hash maps and sets

Learning objective

A map trades memory for speed: remembering what you have seen makes "have I seen this before" a constant-time question.

The concept

A hash map stores values by key, and a set stores just the keys, both with an average lookup of O(1). That single property turns an O(n²) double loop into one pass in dozens of interview questions: "find two numbers that add to a target", "the first non-repeating character", "is there a duplicate", "group the anagrams".

The moving parts: adding a key, checking whether a key exists, reading one back, and counting with counts[x] = counts.get(x, 0) + 1. For a duplicate check a set is enough; for counting or grouping you need the map. In JavaScript a Map is safer than an object when the keys are numbers or come from user input.

Python
def two_sum(nums, target):
    seen = {}                          # value -> index
    for i, n in enumerate(nums):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i
    return []

# "Is there a duplicate?" needs only a set:
def has_duplicate(nums):
    return len(set(nums)) != len(nums)

# A set tells you a value EXISTS; a map tells you WHERE.

Common mistakes

The mistake is using a map when the array is sorted and pointers would do with less memory, or using a set when the question asks for the INDEX of the pair — a set tells you the value exists, not where it was. Read what the question wants returned before choosing the structure.

Worked example

Counting the frequency of each character in a string in one pass with a map is the same building block used by anagrams, duplicates and most "find the first non-repeating" questions.

Your practice task

Solve three frequency problems and one "first non-repeating character" problem, each in a single pass.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

A hash map stores values by key, and a set stores just the keys, both with an average lookup of O(1).

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.