function CountSubstringWithKDistinctChars(s, k) {
let count = 0;
for (let i = 0; i < s.length; i++) {
let ch = s.charAt(i);
let tmp = "" + ch;
let set = new Set();
set.add(ch);
for (let j = i + 1; j < s.length; j++) {
const next_ch = s.charAt(j);
set.add(next_ch);
tmp += next_ch;
if (tmp.length >= k && set.size == k) {
count++;
}
}
}
return count;
}
const str = "characters";
const k = 4;
console.log("Number of substrings with exactly k distinct characters = " + CountSubstringWithKDistinctChars(str, k));
/*
run:
Number of substrings with exactly k distinct characters = 9
*/