Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: For each element, find the next greater element in a circular array (−1 if none).
Problem: For each element, find the next greater element in a circular array (−1 if none).
def nge_circular(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_circular([1, 2, 1]), nge_circular([5, 4, 3, 2, 1]))What is printed?- A. [2, -1, -1] [-1, 5, 5, 5, 5]
- B. [2, -1, 2] [-1, -1, -1, -1, -1]
- C. [2, -1, 2] [-1, 5, 5, 5, 5]
- D. [2, 2, 2] [-1, 5, 5, 5, 5]
Correct answer: C. [2, -1, 2] [-1, 5, 5, 5, 5]
Walk the array twice (indices mod n) so elements near the end can find a greater value at the start; push indices only in the first pass. The last 1 wraps to 2; the maximum never finds anything. O(n).
More Coding Interview Problems questions
- Problem: Compute the stock span: for each day, the number of consecutive days up to today with price ≤ today's price. python def spans(p)…
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…
- Problem: Check whether two strings are isomorphic (characters map one-to-one consistently). python def iso(s, t): return len(set(s)) ==…
- Problem: Find the minimum number of swaps to sort an array of distinct values. python def minswaps(a): order = sorted(range(len(a))…
- Problem: Count the distinct values taken by the bitwise OR of all contiguous subarrays. python def distinctor(a): res, cur = set(), set()…
- Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit. python def maxxor(a): ans = mask = 0…