[LeetCode] Count Integers Appearing in a Single Block

4038. Count Integers Appearing in a Single Block

You are given an integer array nums.

An integer x is special if all occurrences of x in nums appear in a single contiguous block.

Return the number of distinct special integers in nums.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int countSpecialIntegers(vector<int>& nums) {
int last = -1, res = 0;
unordered_map<int,int> freq;
for(auto& n : nums) {
if(last != n) {
freq[n]++;
if(freq[n] == 1) res++;
else if(freq[n] == 2) res--;
}
last = n;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/03/PS/LeetCode/count-integers-appearing-in-a-single-block/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.