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?
- A. A heapq min-heap that stores every value in the window
- B. A list where max() is recomputed over each window
- C. A set of window values with max() recomputed on each step
- 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
- What is the usual fastest way to read n = 10^6 integers from one input line in Python for a judge?
- What is printed? python import heapq print(heapq.nsmallest(2, [5, 1, 4, 1]), list(reversed(range(3))), list(reversed('ab')))
- What is printed? python print(any(map(str.isdigit, 'ab1')), all(map(str.isalpha, 'ab1')))
- What is printed? python print(sorted({'b': 1, 'a': 2}.items()), sum([1, 2, 3], start=10))
- What is printed? python print(max(3, 7, key=lambda v: -v), min('a', 'B'))
- What is printed? python print(str(True) + str(1 == 1.0), type(True + True).name)