Data Structures & AlgorithmsHardGATE CS · DSA
Count distinct values in every window of size k with a frequency map. What is printed?
Count distinct values in every window of size k with a frequency map. What is printed?
from collections import Counter
a, k = [4, 2, 4, 4, 3, 2, 1, 3, 3], 4
c, out = Counter(a[:k]), []
out.append(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)- A. [2, 3, 3, 4, 4, 4]
- B. [2, 3, 3, 4, 3, 3]
- C. [2, 3, 4, 3, 3, 3]
- D. [3, 2, 3, 4, 3, 3]
Correct answer: B. [2, 3, 3, 4, 3, 3]
Keys whose count drops to 0 must be deleted, otherwise len(c) still counts values that left the window. Output: [2, 3, 3, 4, 3, 3].
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is the minimum number of stacks needed to evaluate a fully parenthesised infix expression directly (without converting it first)…
- Merge sort and quick sort are compared. Which statement is correct?
- Bars of width 1 have heights [7, 3, 3, 6, 1, 3, 7, 1, 1]. How many units of rain water are trapped between them (two-pointer method with…
- Bubble sort (ascending; each pass compares adjacent pairs left to right and swaps if out of order) is applied to [49, 52, 21, 37, 35, 19…
- Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed? python s = "aaaaabaaa" z…
- A Python 2-D list is created two ways and one cell is set. What is printed? python a = [[0] 3] 3 b = [[0] 3 for in range(3)] a[0][1] = 5…