awelgorithms

Check whether a map contains a key

Updated

contains-key / has-key is a membership test on the key set. It does not look at values. It is expected O(1), the same hash as get.

What to focus on

Use it when you need a boolean, or when get's miss value could collide with a real stored value.

Worked examples

present

a = [4, 1, 9] as {4:2,1:8,9:3}, has 1
  1. key 1

Result: true

absent

a = [4, 1, 9] as {4:2,1:8,9:3}, has 8
  1. 8 is a value

Result: false

empty

a = [], has 4
  1. no keys

Result: false

Try it

Write hasKey(m, k). m is the hash map. k is the key to test. Return true if k is a key, false if not. Do not look at values. 8 as a value is not a key hit. a = [4, 1, 9] as {4:2,1:8,9:3}, has 1 → true. a = [4, 1, 9] as {4:2,1:8,9:3}, has 8 → false. a = [], has 4 → false.

keys and values are integers. Empty is in the cases.

LeetCode problems that use this skill