Lesson 14/25 ยท ๐Ÿ—‚๏ธ Hash Maps & Sets
๐Ÿ—‚๏ธ Hash Maps & SetsLesson 14/25
Phase 4 ยท Hash Maps & Sets15 min

Hash Sets & Their Patterns

Membership testing in O(1), eliminating duplicates and tracking visited nodes

A set stores unique elements and provides O(1) average-case:
  • add(x), add element
  • x in s, membership test
  • remove(x), remove element

  • Sets are the fastest way to answer "have I seen this before?"
    Longest consecutive sequence, O(n)python
    def longest_consecutive(nums):
        num_set = set(nums)  # O(1) lookups
        longest = 0
    
        for n in num_set:
            # Only start counting from the beginning of a sequence
            if n - 1 not in num_set:
                current = n
                streak = 1
                while current + 1 in num_set:
                    current += 1
                    streak += 1
                longest = max(longest, streak)
    
        return longest
    
    print(longest_consecutive([100, 4, 200, 1, 3, 2]))  # โ†’ 4 (1,2,3,4)
    ๐Ÿค”Quick Check

    You're doing BFS on a graph. Why use a "visited" set instead of a list?

    ๐ŸŽฏ

    Phase Complete!

    Hash Maps & Sets

    Hash maps and sets are some of the most powerful tools in your arsenal. You'll use them in almost every medium/hard interview problem. Now for trees!

    0/500

    Practice Exercises

    0/1 solved
    Exercise 1 of 1easy
    โฑ 00:00

    Happy Number

    A happy number: repeatedly sum the squares of its digits. If you reach 1, it's happy. If you enter a cycle, it's not.
    Expected output: True
    solution.py
    1 / 1
    Solve all 1 exercise to unlock completion