Module 3 · Arrays, Strings and Hashing · Lesson 9 of 40

Solving problems with dicts and sets

Use sets for 'have I seen this?' and dicts for counting and remembering, turning O(n²) ideas into O(n).

In this lesson · about 22 minutes

  • Count things with a dict
  • Find duplicates with a set
  • Solve Two Sum in one pass with a dict

Hash tables are the most useful tool in this whole course. Many slow O(n²) ideas become fast O(n) ideas with a dict or a set.

Set: "have I seen this before?"

A set stores unique items. x in my_set is O(1) on average. Use it to spot duplicates or to remember what you have visited.

Dict: "remember something about each key"

A dict maps keys to values: ages = {"Sara": 12, "Ben": 14}. ages["Sara"] is 12. Use d.get(key, 0) to get a default when the key is missing. Dicts are perfect for counting.

The famous Two Sum problem

Given a list and a target, find two positions whose numbers add up to the target. The slow way checks every pair: O(n²). The fast way walks the list once. For each number, it asks: "Have I already seen the number I need (target - x)?" A dict remembers each number's index, so the answer is instant: O(n).

Try it: count, de-duplicate and Two Sum

Exercise

Any duplicates?

Write has_duplicate(nums) that returns True if any value appears more than once. Use a set so it runs in O(n).

Exercise

Count each letter

Write letter_counts(s) that returns a dict mapping each character in the string to how many times it appears.

Exercise

Are they anagrams?

Two words are anagrams if they use exactly the same letters the same number of times, like "listen" and "silent". Write is_anagram(a, b). Tip: compare their letter counts.

Check your understanding0 of 3 correct

Question 1

1.Which is the best way to check 'have I seen this number before?' many times?

Question 2

2.counts = {}; counts.get('x', 0) returns…

Question 3

3.Two Sum with a dict runs in…

Quiz score: 0 of 3

Exercises solved: 0 of 3

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.