ProgrammingHardCognizant GenC · TCS NQT
What is printed?
What is printed?
def nge(a):
res = [-1] * len(a)
st = []
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. [-1, 2, 4, 4, -1]
- B. [2, 2, 4, -1, -1]
- C. [4, 2, 4, -1, -1]
- D. [4, 4, 4, -1, -1]
Correct answer: C. [4, 2, 4, -1, -1]
The stack holds indices still waiting for a larger value. When a larger value arrives, it pops those indices and records it, so index 0 gets 4 and index 1 gets 2.
More Python Programming questions
- What is printed? python def pickbystart(iv): iv = sorted(iv) cnt, end = 0, -109 for s, e in iv: if s >= end: cnt += 1 end = e return cnt…
- In CPython, which operation on a collections.deque is O(n) in the worst case?
- What is printed? python def primes(n): s = [True] (n + 1) s[0:2] = [False, False] for i in range(2, int(n 0.5) + 1): if s[i]: s[i i::i] =…
- What is printed? python def merge(a, b): i = j = 0 out = [] while i < len(a) and j < len(b): if a[i] <= b[j]: out.append(a[i]) i += 1…
- What is printed? python from collections import deque def maxdist(g): R, C = len(g), len(g[0]) d = [[-1] C for in range(R)] q = deque()…
- What is printed? python from collections import Counter c = Counter('mississippi') print(c.mostcommon(2))