Data Structures & AlgorithmsVery hardCodeforces Div2 D · sliding window

Problem: How many subarrays of [1, 2, 1, 2, 3] contain exactly 2 distinct values? Run the code using the 'at most' trick.

Problem: How many subarrays of [1, 2, 1, 2, 3] contain exactly 2 distinct values? Run the code using the 'at most' trick.
from collections import Counter
def at_most(a, k):
    c = Counter()
    l = res = 0
    for r, x in enumerate(a):
        c[x] += 1
        while len(c) > k:
            c[a[l]] -= 1
            if c[a[l]] == 0:
                del c[a[l]]
            l += 1
        res += r - l + 1
    return res
a = [1, 2, 1, 2, 3]
print(at_most(a, 2) - at_most(a, 1))
What is printed?
  1. A. 7
  2. B. 12
  3. C. 10
  4. D. 6

Correct answer: A. 7

exactly(2) = atMost(2) − atMost(1) = 12 − 5 = 7: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]. Printing atMost(2) alone gives 12, counting 'at least 2 distinct' gives 10, and counting distinct subarray contents instead of positions gives 6.

More Coding Interview Problems questions

Exams that ask this topic