Data Structures19 sections · 729 units
Open in Course

Pattern - Frequency Counting

Counting occurrences

The most common hash map pattern: count how many times each element appears.

freq := empty hash map
for each element in array
    if element in freq
        freq[element] := freq[element] + 1
    else
        freq[element] := 1

After this, freq[x] tells you how many times x appeared. Time: O(n)O(n). Space: O(k)O(k) where kk is the number of distinct elements.