Data Structures19 sections · 729 units
Open in Course

Distinct Values - Add/Remove

Tracking counts

Maintain a frequency array cnt[v]cnt[v] = count of value vv in current range, and distinctCountdistinctCount = number of values with cnt>0cnt > 0.

Add operation:

function add(value)
    if cnt[value] = 0 then
        distinctCount := distinctCount + 1
    cnt[value] := cnt[value] + 1

Remove operation:

function remove(value)
    cnt[value] := cnt[value] - 1
    if cnt[value] = 0 then
        distinctCount := distinctCount - 1

Both are O(1)O(1). Total time: O((n+q)n)O((n + q)\sqrt{n}).