[LeetCode] Find the Largest Almost Missing Integer

3471. Find the Largest Almost Missing Integer

You are given an integer array nums and an integer k.

An integer x is almost missing from nums if x appears in exactly one subarray of size k within nums.

Return the largest almost missing integer from nums. If no such integer exists, return -1.

A subarray is a contiguous sequence of elements within an array.

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int largestInteger(vector<int>& nums, int k) {
int n = nums.size();
unordered_map<int,vector<int>> ord;
for(int i = 0; i < n; i++) ord[nums[i]].push_back(i);
unordered_map<int,int> freq;
for(auto& [x, pos] : ord) {
int cnt = 0, m = pos.size();
for(int i = 0; i < m; i++) {
int le = max(pos[i] - k + 1, 0), ri = min(n - k, pos[i]);
if(i) le = max(le, pos[i-1] + 1);
cnt += max(0, ri - le + 1);
}

freq[x] = cnt;
}
int res = -1;
for(auto& [k,v] : freq) if(v == 1) res = max(res, k);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/02/PS/LeetCode/find-the-largest-almost-missing-integer/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Related Issues not found

Please contact @SongHayoung to initialize the comment