ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
from collections import deque
a = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
dq = deque()
out = []
for i, x in enumerate(a):
while dq and dq[0] <= i - k:
dq.popleft()
while dq and a[dq[-1]] <= x:
dq.pop()
dq.append(i)
if i >= k - 1:
out.append(a[dq[0]])
print(out)- A. [3, 3, -1, 5, 5, 6, 7]
- B. [1, 3, 5, 5, 6, 7]
- C. [3, 3, 5, 3, 6, 7]
- D. [3, 3, 5, 5, 6, 7]
Correct answer: D. [3, 3, 5, 5, 6, 7]
The deque holds indices of a decreasing sequence of values inside the window. The front is always the window maximum, and indices that leave the window are removed from the left, so each step is amortised O(1).
More Python Programming questions
- What is printed? python import heapq class T: def init(self, p, n): self.p = p self.n = n def lt(self, o): return self.p > o.p h = [] for…
- What is printed? python class P: def init(self, x): self.x = x def eq(self, o): return self.x == o.x try: print(len({P(1)})) except…
- What is printed? python from functools import reduce print(reduce(lambda a, b: a b, range(1, 21), 1), reduce(lambda a, b: a + b, [], 0))
- What is printed? python try: print(sorted([3, None, 1])) except TypeError as e: print(e)
- What is printed? python def flat(x): for y in x: if isinstance(y, list): yield from flat(y) else: yield y print(list(flat([1, [2, [3…
- What is printed? python print(len(str(int('7' 4300)))) try: int('7' 4301) except ValueError: print('no')