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?- A. [2, 3, 3, 3, 3]
- B. [2, 2, 3, 3, 3]
- C. [3, 3, 3, 3, 3]
- 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
- Problem: Rotate the array [1, 2, 3, 4, 5, 6, 7] to the right by k = 3 using the three-reversal method. What is printed? python a = [1, 2…
- Problem: How many unordered pairs of distinct elements of [1, 5, 3, 9, 7, 2] have absolute difference exactly 2? Run the code. python a =…
- Problem: Minimum cost to climb stairs where cost[i] is paid when standing on step i and you may take one or two steps. Starting positions…
- Problem: Houses in a circle hold the amounts [2, 3, 2]. You may not rob two adjacent houses, and the first and last are adjacent. Run the…
- Problem: What is the length of the longest common subsequence of 'ABCBDAB' and 'BDCABA'? python a, b = 'ABCBDAB', 'BDCABA' dp = [[0]…
- Problem: The number of structurally distinct binary search trees on 5 keys is the Catalan number. What does this code print? python dp =…