awelgorithms

Build a frequency map

Updated

A frequency map is value → count. One pass: for each x, put x → getOrDefault(x,0)+1. Unseen keys are absent (count 0), not stored as zeros.

What to focus on

This is the map version of a frequency table. Huge or sparse values cannot use an array of size max(a).

Worked examples

repeats

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

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

all same

a = [2, 2, 2]
  1. 2:3

Result: {2:3}

empty

a = []
  1. no keys

Result: {}

Try it

Write freqMap(a). a is an array of integers. Return value → count. Unseen keys are absent, not stored as zeros. Then look up count of 1 on the first map. a = [4, 1, 9, 1] → {4:1, 1:2, 9:1}. a = [2, 2, 2] → {2:3}. a = [] → {}.

a is a list of integers and may be empty.

LeetCode problems that use this skill