Skip to content
CodeItRaw
Hashing

Lesson 5/5

A list takes you from a place to a value: values[3]. Sometimes you need the reverse: "where was the value 7?" Write the value as the key and the place as the value in a dictionary and you answer that in one step.

seen = {}
for i, v in enumerate(values):
if key - v in seen:
return [seen[key - v], i]
seen[v] = i
return []
Looking for two numbers that add up to key, each element has exactly one possible partner: key - v. If you have seen that partner, take its place from the dictionary. Ask first, then write: that way an element never pairs with itself.

This pattern ("have I seen what I am looking for, and if so where") is the skeleton of a large share of interview questions.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Two Sum

    Function

  2. 02

    Two Sum

    Code reading · Review the AI

If you would rather not wait for the order, every problem is open without locks: Problem list