Data Structures & Algorithms Hash Maps & Sets
💡
Exercise 28

HashMap Basics 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

A Hash Map (dictionary in Python) is perhaps the MOST important data structure in coding interviews. It gives O(1) average lookup! 🗂️

💡 Think of it like this: Imagine a library where every book has a unique code. Instead of searching every shelf, you type the code into a computer and it tells you the EXACT location instantly. That's a hash map — it maps keys to values in constant time!

# Python dictionary = hash map phonebook = { 'Alice': '555-1234', 'Bob': '555-5678', 'Charlie': '555-9999' } print(phonebook['Alice']) # '555-1234' — O(1) lookup! phonebook['Dave'] = '555-0000' # Add new entry — O(1) print('Bob' in phonebook) # True — O(1) check del phonebook['Charlie'] # Delete — O(1)

Hash Map operations (all O(1) average):

  • 📖 Lookup: d[key] or d.get(key, default)
  • ✏️ Insert/Update: d[key] = value
  • 🗑️ Delete: del d[key]
  • 🔍 Check existence: key in d

The #1 pattern: "Have I seen this before?" — Store things as you go and check for them in O(1):

# Two Sum — the quintessential hashmap problem def twoSum(nums, target): seen = {} # val → index for i, num in enumerate(nums): complement = target - num if complement in seen: # Seen before? Match! return [seen[complement], i] seen[num] = i # Remember this number

If you see a problem asking about counting, grouping, finding duplicates, or pairing — think hash map first!

📋 Instructions
Create a dictionary that maps fruit names to their colors: - 'apple' → 'red' - 'banana' → 'yellow' - 'grape' → 'purple' Then print the color of 'banana' using the dictionary.
Create the dictionary with {} syntax, then access with dict['banana']. You've got this — take it step by step!
🧪 Test Cases
Input
Run your code
Expected
yellow
Expected program output
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.