awelgorithms

Recognize a frequency query

Updated

Frequency queries ask how many, most or least common, whether two bags match, whether you can form a word from counts. Recipe: one pass to value→count, then a scan of the map or a second pass of queries.

What to focus on

Existence of a duplicate is weaker (a set). Need every index of a value is grouping, not a scalar count. Tiny alphabets can swap in an array table.

Worked examples

mode

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

Result: freq map then max

anagram bags

a = [1, 4, 1], b = [4, 1, 1]
  1. same counts

Result: compare two freq maps

not freq

a = [4, 1, 9, 1], only 'is 1 there twice?' can early-exit
  1. set or first repeat

Result: full freq optional

Try it

Write modeKey(a). a is an array of integers. Build a frequency map, then return the key with the largest count. Bag equality compares two frequency maps. A yes/no duplicate check may not need the full map. a = [4, 1, 9, 1] → freq map then max. a = [1, 4, 1], b = [4, 1, 1] → compare two freq maps. a = [4, 1, 9, 1], only 'is 1 there twice?' can early-exit → full freq optional.

a is a non-empty list of integers. When two arrays appear, both are non-empty.