Amazon | OA 2019 | Substrings with exactly K distinct chars

link

992. Subarrays with K Different Integers

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
class Solution {
static int subarraysWithKDistinct(int[] A, int K) {
return atMostK(A, K) - atMostK(A, K - 1);
}

static int atMostK(int[] A, int K) {
int start = 0, end = 0;
int len = 0;
Map<Integer, Integer> map = new HashMap<>();

while (end < A.length) {
int endNum = A[end];
map.put(endNum, map.getOrDefault(endNum, 0) + 1);
end++;
while (map.size() > K) {
int startNum = A[start];
map.put(startNum, map.get(startNum) - 1);
if (map.get(startNum) == 0) {
map.remove(startNum);
}
start++;
}
len += end - start;
}
return len;
}
}

0%