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?- A. 7
- B. 12
- C. 10
- 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
- Problem: Dijkstra from 0 with edges (0,1,1), (1,3,2), (0,2,4), (2,3,1). Which vertex sequence is the shortest path from 0 to 3? Run the…
- Problem: Is the graph with edges forming the 5-cycle 0-1-2-3-4-0 bipartite? And is the 4-cycle 0-1-2-3-0 bipartite? Run the BFS colouring…
- Problem: Tree with edges 0-1, 0-2, 1-3, 1-4, 2-5. How many nodes are in the subtree of node 1 (rooted at 0)? Run the DFS code. python…
- Problem: Which statement about Fenwick (binary indexed) trees is false?
- Problem: Items have small values (at most 1000 each, n = 100) but very large weights (up to 10^9), and capacity W = 10^9. Which DP is…
- Problem: For n = 10^5 elements and q = 10^5 queries, a sqrt-decomposition answers each query in O(sqrt n). Roughly how many elementary…