ProgrammingHardAmazon OA · Flipkart coding round

For a sliding-window maximum over an array of n = 2 * 10^5 values, which Python structure gives an O(n) total algorithm?

  1. A. A heapq min-heap that stores every value in the window
  2. B. A list where max() is recomputed over each window
  3. C. A set of window values with max() recomputed on each step
  4. D. collections.deque used as a monotonic queue of indices

Correct answer: D. collections.deque used as a monotonic queue of indices

A deque of indices in decreasing value order gives the window maximum at the front. Each index is added and removed at most once, so the total is O(n).

More Python Programming questions

Exams that ask this topic