awelgorithms

Find the most frequent key

Updated

Scan the map (or track best while building) for the max count. Ties need a rule: first-seen, smallest key, or any.

What to focus on

Do not scan the original array again if you already have the map unless you need first-seen and did not store order.

Worked examples

clear winner

a = [4, 1, 9, 1]
  1. 1 has 2

Result: mode key 1

tie first-seen

a = [2, 3, 2, 3]
  1. 2 and 3 both 2
  2. 2 appeared first

Result: mode 2 under first-seen

all unique

a = [4, 1, 9]
  1. every count 1
  2. first-seen 4

Result: mode 4 (tie rule)

Try it

Write modeKey(a). a is an array of integers. Build a frequency map. Return the key with the largest count. Ties use first-seen. a = [4, 1, 9, 1] → mode key 1. a = [2, 3, 2, 3] → mode 2 under first-seen. a = [4, 1, 9] → mode 4 (tie rule).

a is a non-empty list of integers. Ties use first-seen.