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?

  1. A. Rebuild a set for each window, O(n*k) total
  2. B. Sort each window, O(n*k log k) total
  3. C. Create a fresh Counter per window and take its length, O(n*k) total
  4. 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

Exams that ask this topic