CODE THE HERO

Home › Learn › World 3: Hash Harbor

FREE

Frequency Board

Counting with a hash map, O(n)

Level 3.3 of Code the Hero, in Hash Harbor: hash maps: find anything in one visit.

The idea

A hash map from item to count builds a frequency table in one pass — the basis of anagram, majority and top-k problems.

The mission

The harbor board must show how many of each cargo arrived today. Use each cargo name as a key. Its locker holds the count so far. New cargo? Start at 1. Seen before? Add 1 to what's already there.

Goal: When your code ends, each cargo's locker must hold how many times it arrived.

The commands you get

You write real Python, Java or JavaScript. These are the moves the hero understands in this level:

parcels.length / parcels.get(i)Read cargo i's name
lockers.get(key)Count so far, or undefined if none
lockers.put(key, value)Store the new count

What it costs

TimeO(n)
SpaceO(distinct items)

How the stars are earned

  1. Correct board on every test
  2. At most 2n reads
  3. At most n reads

Your code is also checked on hidden inputs, so it has to work for any case, not only the one on screen.

▶ Play this level free

No sign-up. Levels open in order, so if this one is still locked you start at the first level that isn't.

More in Hash Harbor