ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
def nge(a):
st, res = [], [-1] * len(a)
for i, x in enumerate(a):
while st and a[st[-1]] < x:
res[st.pop()] = x
st.append(i)
return res
print(nge([2, 1, 2, 4, 3]))- A. [4, 4, 4, -1, -1]
- B. [4, 2, 4, -1, -1]
- C. [4, 2, 4, 4, -1]
- D. [2, 4, 4, -1, -1]
Correct answer: B. [4, 2, 4, -1, -1]
A monotonic stack finds each element's next greater value. 2 is followed by 4, the 1 is followed by 2, the second 2 is followed by 4, and 4 and 3 have no greater value to their right.
More Python Programming questions
- What is printed? python from itertools import takewhile, dropwhile a = [1, 3, 4, 6, 7, 9] print(list(takewhile(lambda x: x % 2, a))…
- What is printed? python def f(): try: return 'try' finally: print('finally', end=' ') print(f())
- What is printed? python def g(): try: return 1 finally: return 2 print(g())
- What is printed? python def bracketok(s): pairs = {')': '(', ']': '[', '}': '{'} st = [] for ch in s: if ch in '([{': st.append(ch) elif…
- What is printed? python import sys data = 'first line nsecondn' it = iter(data.splitlines()) print(repr(next(it)), repr(next(it).strip())…
- What is printed? python from collections import deque q = deque() for ch in 'abcd': q.append(ch) if len(q) > 2: q.popleft()…