awelgorithms

Distinguish a map from a set

Updated

A set stores membership: 4 is in or out. A map stores a payload per key: 4 maps to 2. If the problem never asks what is stored for 4, a set is enough. Counts, indices, and groups need a map.

What to focus on

contains(4) is a set (or contains-key). get(4) is a map. Frequency is a map from value to count. A set of values cannot answer how many 4s.

Worked examples

membership only

a = [4, 1, 9], need = membership
  1. need in-or-out

Result: "set"

payload

a = [4, 1, 9], need = firstIndex
  1. 4→0, 1→1, 9→2

Result: "map"

counts

a = [4, 1, 9, 1], need = counts
  1. 1 appears twice

Result: {"4":1,"1":2,"9":1}

Try it

Write chooseStructure(a, need). a is an array of integers. need is "membership", "firstIndex", or "counts". Return "set" for membership, "map" for firstIndex, and the frequency object for counts. a = [4, 1, 9], membership → "set". firstIndex → "map". a = [4, 1, 9, 1], counts → {"4":1,"1":2,"9":1}.

a is a non-empty list of integers.