awelgorithms

Build a hash map from pairs

Updated

Building from two parallel lists means put a[i]→b[i] for each i. Later pairs with the same key overwrite earlier ones.

What to focus on

Keys [4,1,9] and values [2,8,3] become {4:2, 1:8, 9:3}. If a key repeats, the last value wins.

Worked examples

three pairs

a = [4, 1, 9], b = [2, 8, 3]
  1. put in order

Result: {4:2, 1:8, 9:3}

repeat key

a = [4, 1, 4], b = [2, 8, 3]
  1. 4→2 then 4→3 overwrites

Result: {4:3, 1:8}

empty

a = [], b = []
  1. no puts

Result: {}

Try it

Write fromPairs(a, b). a is the list of keys. b is the list of values, same length. Put a[i]→b[i] in order. Last write wins for a repeated key. Return the map. a = [4, 1, 9], b = [2, 8, 3] → {4:2, 1:8, 9:3}. a = [4, 1, 4], b = [2, 8, 3] → {4:3, 1:8}. a = [], b = [] → {}.

a and b are equal-length lists of integers and may be empty.