Maintain a frequency array = count of value in current range, and = number of values with .
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 . Total time: .