Data Structures & AlgorithmsHardProduct Company SDE · sliding window OA

Problem: What is the length of the longest contiguous subarray containing at most two distinct values?

Problem: What is the length of the longest contiguous subarray containing at most two distinct values?
from collections import Counter
def f(a):
    c = Counter()
    l = best = 0
    for r, x in enumerate(a):
        c[x] += 1
        while len(c) > 2:
            c[a[l]] -= 1
            if c[a[l]] == 0:
                del c[a[l]]
            l += 1
        best = max(best, r - l + 1)
    return best
print(f([1, 2, 1, 2, 3, 2, 2, 4, 1]))
What is printed?
  1. A. 5
  2. B. 3
  3. C. 4
  4. D. 6

Correct answer: C. 4

The windows [1,2,1,2] and [2,3,2,2] both have length 4 and no longer window has only two values. The two-pointer window shrinks until only two distinct values remain.

More Coding Interview Problems questions

Exams that ask this topic