ProgrammingModerateTCS NQT · Accenture
For an array of n = 10^5 values, which approach counts the distinct values in every window of size k = n / 2 in the least total time?
- A. Rebuild a set for each window, O(n*k) total
- B. Sort each window, O(n*k log k) total
- C. Create a fresh Counter per window and take its length, O(n*k) total
- D. Keep a dict of counts, add the entering value and remove the leaving one, O(n) total
Correct answer: D. Keep a dict of counts, add the entering value and remove the leaving one, O(n) total
A running count dictionary updates in O(1) per step as values enter and leave the window, so the whole pass is O(n). The other approaches redo O(k) work for every window.
More Python Programming questions
- What is printed? python a = [1, 2, 3, 4] try: print(a[len(a) / 2]) except TypeError: print('TypeError') print(a[len(a) // 2])
- What is printed? python s = 'u00b2' print(s.isdigit(), s.isdecimal(), s.isnumeric())
- What is printed? python d = {1: 'a'} d[1.0] = 'b' d[True] = 'c' print(d)
- What is printed? python def acc(): total = 0 while True: x = yield total if x is None: return total total += x g = acc() next(g) g.send(5)…
- What is printed? python class P: def init(self, x): self.x = x def eq(self, o): return self.x == o.x try: s = {P(1)} except TypeError…
- What is printed? python class S: slots = ('a',) s = S() s.a = 1 try: s.b = 2 except AttributeError: print('no dict', s.a)