[InterviewBit] Subarrays with distinct integers!

Subarrays with distinct integers!

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int Solution::solve(vector<int> &A, int B) {
int res = 0;
unordered_map<int, int> freq;
unordered_map<int, int> mi;
int l = 0, r = 0, m = 0, n = A.size();
while(r < n) {
while(r < n and freq.size() <= B) {
if(freq.size() == B) {
int m = l;
unordered_map<int, int> now;
while(m < r and freq[A[m]] - now[A[m]] > 1) {
now[A[m]] += 1;
m += 1;
}
res += m - l + 1;
}
freq[A[r]] += 1;
r += 1;
}
while(l < r and freq.size() > B) {
if(--freq[A[l]] == 0) freq.erase(A[l]);
l += 1;
}
}
if(freq.size() == B) {
int m = l;
unordered_map<int, int> now;
while(m < r and freq[A[m]] - now[A[m]] > 1) {
now[A[m]] += 1;
m += 1;
}
res += m - l + 1;
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/09/PS/interviewbit/subarrays-with-distinct-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.