Day 75: :key: Mastering HashMaps for Problem Solving in DSA

If you’re diving into coding interviews or just want to level up your DSA skills, HashMaps (aka Hash Tables or Dictionaries) are a tool you need in your toolkit. They’re fast, flexible, and surprisingly fun to use once you get the hang of them.

:rocket: Why HashMaps Matter

HashMaps let you store key-value pairs and access them in O(1) time. That’s a game-changer when you’re trying to solve problems quickly and efficiently.

Think of them as smart lockers—you instantly know where the key is without checking every locker.

:bulb: Common Use Cases

Counting elements

→ E.g. {‘a’: 2, ‘b’: 1}

:repeat: For problems like “First Unique Character”

Tracking indices

→ For “Two Sum”, store value → index

Avoiding repeated work

→ Use it in memoization during recursion

:brain: Example Problem: Two Sum (Classic)

Problem: Given an array and a target, return the indices of two numbers that add up to the target.

js

CopyEdit

const twoSum = (nums, target) => {

const map = {};

for (let i = 0; i < nums.length; i++) {

const diff = target - nums[i];

if (map[diff] !== undefined) {

  return [map[diff], i];

}

map[nums[i]] = i;

}

};

:white_check_mark: Uses a HashMap to check for the complement in O(1)

:hammer_and_wrench: Pro Tip

Always ask yourself:

“Can I reduce the time complexity if I use a map to track values?”

:books: Bonus Challenge to Try

Find the length of the longest substring without repeating characters.

Hint: You’ll need a HashMap AND a sliding window :wink:

100daysofcode lebanon-mug