Data Structures & AlgorithmsHardGATE CS · DSA

Count distinct values in every window of size k with a frequency map. What is printed?

Count distinct values in every window of size k with a frequency map. What is printed?
from collections import Counter
a, k = [4, 2, 4, 4, 3, 2, 1, 3, 3], 4
c, out = Counter(a[:k]), []
out.append(len(c))
for i in range(k, len(a)):
    c[a[i]] += 1; c[a[i - k]] -= 1
    if c[a[i - k]] == 0: del c[a[i - k]]
    out.append(len(c))
print(out)
  1. A. [2, 3, 3, 4, 4, 4]
  2. B. [2, 3, 3, 4, 3, 3]
  3. C. [2, 3, 4, 3, 3, 3]
  4. D. [3, 2, 3, 4, 3, 3]

Correct answer: B. [2, 3, 3, 4, 3, 3]

Keys whose count drops to 0 must be deleted, otherwise len(c) still counts values that left the window. Output: [2, 3, 3, 4, 3, 3].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic