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?- A. 5
- B. 3
- C. 6
- 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
- Problem: Find the length of the longest substring that can be turned into a single repeated letter by changing at most k characters…
- Problem: Return the smallest window of s that contains every character of t (with multiplicity). python from collections import Counter…
- Problem: A username is valid if it reads the same forwards and backwards after removing non-alphanumeric characters and ignoring case…
- Problem: Return True if one character can be deleted from a word to make it a palindrome (or it already is one). python def almost(s): def…
- Problem: Compress a string by replacing each run with the letter followed by the run length (only when the run is longer than 1). python…
- Problem: Reverse the order of words in a sentence, collapsing multiple spaces. python s = " the sky is blue " print("|" + "…