Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Count how many substrings of length k in a DNA string contain exactly k distinct letters.

Problem: Count how many substrings of length k in a DNA string contain exactly k distinct letters.
def count_distinct(s, k):
    freq, c = {}, 0
    for i, ch in enumerate(s):
        freq[ch] = freq.get(ch, 0) + 1
        if i >= k:
            out = s[i - k]
            freq[out] -= 1
            if freq[out] == 0:
                del freq[out]
        if i >= k - 1 and len(freq) == k:
            c += 1
    return c
print(count_distinct("ACGTACCA", 3))
What is printed?
  1. A. 5
  2. B. 3
  3. C. 6
  4. D. 4

Correct answer: D. 4

Windows of length 3: ACG ✓, CGT ✓, GTA ✓, TAC ✓, ACC ✗, CCA ✗ → 4. Deleting keys whose count drops to 0 keeps len(freq) equal to the number of distinct letters; forgetting the del makes ACC and CCA look distinct too (count 6). O(n).

More Coding Interview Problems questions

Exams that ask this topic