Skip to content
CodeItRaw
Path

Counting and remembering with dicts and sets, turning O(n²) into O(n).

Key ideas

  • A set answers "have I seen this?" in O(1).
  • A dict is for counting and for going from a value to its index.
  • When you see two nested loops, ask whether a dict can replace the inner one.

Pattern

count = {}
for v in values:
    count[v] = count.get(v, 0) + 1

Finish these first:Arrays

Lessons

Each lesson explains one idea from zero and ends with a few tasks. Lessons open in order; the explanation can be read at any time.

  1. 01

    Sets: have I seen this?

    0/3 tasks

  2. 02

    How many different values?

    0/3 tasks

  3. 03

    Counting with a dictionary

    0/3 tasks

  4. 04

    Two passes: count first, then ask

    0/3 tasks

  5. 05

    From a value to its place

    0/2 tasks

Boss

  • 06

    Longest Streak

    Function

  • The boss opens when every lesson of the topic is finished. Solve it too and the topic is complete, and the topics after it open.