Data Structures & AlgorithmsVery hardProduct company OA
Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). What is printed?
Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). What is printed?
def nge_circ(a):
n = len(a); res = [-1] * n; st = []
for i in range(2 * n):
x = a[i % n]
while st and a[st[-1]] < x: res[st.pop()] = x
if i < n: st.append(i)
return res
print(nge_circ([3, 8, 4, 1, 2, 8, 0]))- A. [8, -1, 8, 2, 8, -1, -1]
- B. [8, -1, 8, 2, 8, 8, 3]
- C. [8, 8, 8, 2, 8, -1, 3]
- D. [8, -1, 8, 2, 8, -1, 3]
Correct answer: D. [8, -1, 8, 2, 8, -1, 3]
The second lap lets elements near the end find a larger value at the front. 0 at the end wraps around to 3. Both 8s are the maximum, and 'greater' is strict, so neither finds anything (−1); treating equal as greater gives the option with an 8 for index 5. Each index is pushed once and popped at most once, so 2n iterations total – O(n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Towers stand in a row. Two towers can see each other if every tower strictly between them is shorter than both. The function counts such…
- A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros…
- Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign…
- Longest subarray with sum exactly 5 when the array contains NEGATIVE numbers: a shrink-when-too-big sliding window versus a prefix-sum map…
- Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?…
- A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed? python def…