Data Structures & AlgorithmsModerateProduct Company SDE · sliding window OA

Problem: What does the following print? It counts distinct values in each window of size 3.

Problem: What does the following print? It counts distinct values in each window of size 3.
from collections import Counter
a = [1, 2, 1, 3, 4, 2, 3]
k = 3
c = Counter(a[:k])
out = [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)
What is printed?
  1. A. [2, 3, 3, 3, 3]
  2. B. [2, 2, 3, 3, 3]
  3. C. [3, 3, 3, 3, 3]
  4. D. [2, 3, 2, 3, 3]

Correct answer: A. [2, 3, 3, 3, 3]

Windows are [1,2,1], [2,1,3], [1,3,4], [3,4,2], [4,2,3] with 2, 3, 3, 3, 3 distinct values. Deleting keys whose count reaches zero keeps len(c) equal to the distinct count.

More Coding Interview Problems questions

Exams that ask this topic