Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count subarrays whose maximum lies in [L, R] in one pass.
Problem: Count subarrays whose maximum lies in [L, R] in one pass.
def count(a, L, R):
last_bad = last_ok = -1; res = 0
for i, x in enumerate(a):
if x > R: last_bad = i
if x >= L: last_ok = i
res += max(0, last_ok - last_bad)
return res
print(count([3, 1, 6, 2, 9, 4, 5], 3, 6))What is printed?- A. 10
- B. 28
- C. 11
- D. 13
Correct answer: C. 11
For each right end i, valid left ends lie after the last element > R and at or before the last element ≥ L, giving last_ok − last_bad choices. The 9 resets everything; the total 11 matches checking all 28 subarrays.
More Coding Interview Problems questions
- Problem: Shortest path (in steps) from the top-left to the bottom-right cell of a grid where 1 is a wall, if you may remove at most k…
- Problem: A lock has 4 wheels of digits 0–9; one move turns one wheel by ±1 (wrapping 9↔0). Starting at '0000', find the fewest moves to…
- Problem: Water level t floods every cell of height ≤ t. Find the smallest t at which you can swim from the top-left to the bottom-right…
- Problem: Connect all points with minimum total Manhattan-distance wiring (dense-graph Prim in O(n²)). python def mst(p): n = len(p); dist…
- Problem: Courses with prerequisites (u → v means u before v); any number of courses can be taken per semester. Find the minimum number of…
- Problem: Answer lowest-common-ancestor queries with binary lifting (up[j][v] = 2^j-th ancestor). python par = [-1, 0, 0, 1, 1, 2, 3, 3, 4…