Data Structures & AlgorithmsHardProduct Company SDE · stack round
Problem: What does the following print? It returns the next greater element of each position in a circular array (search continues from the start).
Problem: What does the following print? It returns the next greater element of each position in a circular array (search continues from the start).
def nge(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([1, 2, 1]))- A. [2, -1, 2]
- B. [2, -1, -1]
- C. [2, 2, -1]
- D. [1, 2, 2]
Correct answer: A. [2, -1, 2]
Index 0 finds 2, index 1 has no larger value anywhere, and index 2 wraps around to find 2. Stopping the scan at n instead of 2n produces the trap [2, -1, -1].
More Coding Interview Problems questions
- Problem: How many cells of a 3 x 3 grid are at exactly 2 steps (4-directional moves, no obstacles) from the top-left cell? Run the BFS…
- Problem: How many ordered pairs (a, b) with 1 <= a, b <= 6 have gcd(a, b) = 1? python from math import gcd print(sum(1 for a in range(1…
- Problem: What does the following print? python print(sum(bin(i).count('1') for i in range(1, 16)))
- Array a = [5, -3, 2, 4, -6, 1, 3, -2]. How many non-empty contiguous subarrays have a sum in the closed range [0, 4]?
- For the string s = "aabbabbaab", find the length of the longest substring with exactly as many letter a as letter b.
- For the array a = [4, 1, 7, 2, 2, 5, 3, 6], how many contiguous non-empty subarrays have XOR equal to 0? Use prefix XOR values.