# Count of substrings of length K with exactly K distinct characters ###### tags: `Sliding window`, `Amazon OA` Description: Given string `str` of the lowercase alphabet and an integer `k`, the task is to count all substrings of length `k` which have exactly `k` distinct characters. Solution: ```java= public class kLengthDistinctCharSubstring { public int countSubstrings(String str, int k) { int res = 0; int[] arr = new int[26]; int l = 0; int r = 0; // change the cnt while moving the pointers while (r < str.length()) { // count the char at pointer r char c = str.charAt(r); ++arr[c - 'a']; // move left pointer in the following scenarios: // 1. number of char at r is larger than 2 // 2. length of substring > k while (arr[c - 'a'] > 1 || r - l + 1 > k) { --arr[str.charAt(l++) - 'a']; } if (r - l + 1 == k) { res++; } r++; } return res; } } ```