Data Structures & AlgorithmsHardProduct Company SDE · stack round
Problem: Sum the values of the next greater element of each position in [2, 1, 4, 3], where a position with no greater element contributes 0. Run the code.
Problem: Sum the values of the next greater element of each position in [2, 1, 4, 3], where a position with no greater element contributes 0. Run the code.
a = [2, 1, 4, 3]
res = [0] * len(a)
st = []
for i, x in enumerate(a):
while st and a[st[-1]] < x:
res[st.pop()] = x
st.append(i)
print(sum(res))What is printed?- A. 8
- B. 7
- C. 4
- D. 9
Correct answer: A. 8
The next greater values are 4 for 2, 4 for 1 and 0 for the two larger elements (4 and 3 have none), totalling 8. Counting the untouched positions as -1 changes the sum.
More Coding Interview Problems questions
- Problem: Using at most one flip of a 0 to 1, what is the longest run of consecutive 1s in [1, 0, 1, 1, 0, 1]? Run the sliding-window code…
- Problem: How many unordered pairs of words in ['abc', 'bca', 'xyz', 'cab'] are anagrams of each other? Run the code. python from itertools…
- Problem: How many subsets of [1, 2, 3, 4, 5] have a sum of exactly 7? Run the code. python from itertools import combinations a = [1, 2…
- Problem: What is the length of the longest arithmetic subsequence of [1, 3, 5, 7, 4]? Run the O(n^2) DP code. python a = [1, 3, 5, 7, 4] n…
- Problem: What is the minimum path sum from the top to the bottom of the triangle [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]], moving to an…
- Problem: How many unordered pairs (i < j) of 1..10 have a sum divisible by 5? Run the code. python a = list(range(1, 11)) print(sum(1 for…