awelgorithms

Membership only is a set

Updated

If the problem never asks for a payload — no count, no index, no group list, no value stored for k — a set is the structure. A map with dummy values true or 1 is a set using extra memory.

What to focus on

contains(x) is a set. get(x) is a map. Two-sum existence can be a set. Two-sum indices cannot. Frequency cannot.

Worked examples

seen

a = [4, 1, 9, 1], ask 'have I seen 1?'
  1. in or out

Result: set

first index

a = [4, 1, 9, 1], ask 'where is 1?'
  1. payload is an index

Result: map 1→1

empty

a = []
  1. either structure is empty

Result: set {} and map {} both work and both miss

Try it

Write chooseStructure(a, question). a is an array of integers. question is what you need to answer. Return "set" when you only need in-or-out. Return "map" when you need an index or a count. Dummy true is not a reason to use a map. a = [4, 1, 9, 1], ask 'have I seen 1?' → set. a = [4, 1, 9, 1], ask 'where is 1?' → map 1→1. a = [] → set {} and map {} both work and both miss.

a is a list of integers and may be empty.